背景:上传图片需要是base64格式
代码:第一次转换得到base64为空值
var imgFile = new Image()
imgFile.src="./ceshi.jpeg"
//转base64
var canvas = document.createElement( "canvas" );
canvas.width = imgFile.width;
canvas.height = imgFile.height;
var ctx = canvas.getContext( "2d" );
ctx.drawImage(imgFile, 0 , 0 , imgFile.width, imgFile.height);
var ext = imgFile.src.substring(imgFile.src.lastIndexOf( "." )+ 1 ).toLowerCase();
var dataURL = canvas.toDataURL( "image/" +ext);
为了解决第一次转换就成功就用了onload监听是否成功
var imgFile = new Image()
imgFile.src="./ceshi.jpeg"
imgFile.onload=()=>{
console.log(imgFile,11)
//转base64
var canvas = document.createElement( "canvas" );
console.log('canvas---',canvas)
canvas.width = imgFile.width;
canvas.height = imgFile.height;
var ctx = canvas.getContext( "2d" );
ctx.drawImage(imgFile, 0 , 0 , imgFile.width, imgFile.height);
var ext = imgFile.src.substring(imgFile.src.lastIndexOf( "." )+ 1 ).toLowerCase();
var dataURL = canvas.toDataURL( "image/" +ext);
}
但是这里要注意一下:img.onload方法是一个异步函数,所以在外部取onload方法里面的值会有拿不到的情况。