<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的方法如下:
<!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>
复制代码