2014-06-10 70 views
0

我正在调整图像使用画布和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

onload是“onloadend”。一旦图像完全加载,它就会被触发。图像没有其他加载事件。 –

+0

只需要在你的最后调整大小... – csanonymus

+0

我在onload中放了几个日志语句......它们被多次触发 – thebiglebowski11

回答

0

的图像被异步加载,但...

内.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(); 
}