2014-06-10 68 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(); 
}