<canvas id="canvas" width="300" height="300"></canvas>複製代碼
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//建立img對象
var img=new Image();
img.src="./img/icon.jpg";
// 添加onload避免異步問題
img.onload = function () { ctx.drawImage(img,0,0,200,200);
ctx.fillRect(10,10,10,10)
var dataURL = canvas.toDataURL();//轉成base64
console.log(dataURL);
};複製代碼
文件轉base64的方法以下:javascript
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="file" id="file"> <div class="base64"></div> <script> var file=document.getElementById("file"); file.onchange=function () { //建立文件讀取的實例 var reader=new FileReader(); //轉碼base64 reader.readAsDataURL(file.files[0]); reader.onload=function(){ document.getElementsByClassName("base64")[0].innerHTML=this.result; } } </script> </body> </html> 複製代碼