1 回答
TA贡献1775条经验 获得超8个赞
img.onload是一个异步方法,所以需要在该方法中获取dataUrl
function compressImg(url){
var newimg=document.querySelector('.img');
var dataUrl='';
var size=url.length/1024-url.length/4096;
var scale=500/size;
if(size > 500){
var img = new Image();
img.src=url;
var canvas=document.createElement('canvas');
var ctx=canvas.getContext('2d');
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0,canvas.width,canvas.height);
dataUrl=canvas.toDataURL('image/jpeg',scale);
newimg.src=dataUrl;
}
}else{
newimg.src=url
}
}
添加回答
举报