我正在使用canvas和javascript调整图像大小...图像完成后,我想做一些逻辑。有没有完成的活动?我尝试过onloadend但它永远不会被调用:
var fr = new FileReader();
fr.onload = function (e) {
var img = new Image();
img.onloadend = function() {
console.log('finished logic here');
}
img.onload = function(){
var MAXWidthHeight = 488;
var ratio = MAXWidthHeight / Math.max(this.width,this.height);
var w = this.width * ratio;
var h = this.height * ratio;
var c = document.createElement("canvas");
c.width = w;
c.height = h;
c.getContext("2d").drawImage(this,0,0,w,h);
this.src = c.toDataURL();
document.body.appendChild(this);
}
img.src = e.target.result;
}
fr.readAsDataURL(files[i]);
答案 0 :(得分:1)
图像是异步加载的,但是......
.onload中的所有处理都是同步的,所以你可以像这样添加一个回调:
img.onload = function(){
var MAXWidthHeight = 488;
var ratio = MAXWidthHeight / Math.max(this.width,this.height);
var w = this.width * ratio;
var h = this.height * ratio;
var c = document.createElement("canvas");
c.width = w;
c.height = h;
c.getContext("2d").drawImage(this,0,0,w,h);
this.src = c.toDataURL();
document.body.appendChild(this);
// after this img has been appended, execute myCallback()
myCallback();
}
function myCallback(){
console.log("I'm called after this img has been appended");
}
如果加载多个图像,则会有多个.onloads,因此您将多次执行myCallback。如果你只想在追加所有图像后执行一次myCallback,你可以设置一个倒计时变量来延迟调用myCallback,直到所有图像都被追加为止。
var countdown=imageCount; // imageCount is the total count of images to be processed
// and then in .onload
if(--countdown==0){
myCallback();
}