2013-04-29 50 views
0
var canvas = null; 
var context = null; 
var img = null; 
var frames = []; 
var assets = []; 
var imgLoadCount = 0; 

setup = function (fileArray) { 
    assets = fileArray; 
    //Loading an image 
    for(var i = 0; i < assets.length; i++) { 
    console.log(i); 
    frames.push(new Image()); // declare image object 
    frames[i].onload = onImageLoad(assets.length); //declare onload method 
    frames[i].src = URL.createObjectURL(assets[i]); //set url 
    } 
}; 

onImageLoad = function (len) { 
    console.log("IMAGE!!!"); 
    canvas = document.getElementById("my_canvas"); //creates a canvas element 
    context = canvas.getContext('2d'); 
    canvas.width = window.innerWidth; //for full screen 
    canvas.height = window.innerHeight; 
    var x, y, numTilesRow; 
    numTilesRow = 10; 
    imgLoadCount++; 
    console.log("imgLoadCount = " + frames.length + ", length = " + len); 
    if(imgLoadCount != len) { 
    return; 
    } 
    for(var index = 0; index < len; index++) { 
    x = Math.floor((index % numTilesRow)); 
    y = Math.floor(index/numTilesRow); 
    worldX = x * numTilesRow; 
    worldY = y * numTilesRow; 
    context.drawImage(frames[index], worldX, worldY); 
    } 
}; 

我不能告訴的drawImage爲什麼突然停止插入代碼 後工作,如果(imgLoadCount = LEN!){回報;}這將確保所有圖像加載正確。請有人幫我找到解決這個問題的方法。的drawImage不工作

+0

愚蠢的問題,但你檢查看到'imgLoadCount == len'? – 2013-04-29 06:54:32

+0

是的,下面的for循環只在imgLoad === len時才運行,這是所有圖像加載時的情況,因此drawImage需要在循環的每次運行中繪製圖像,但不會。這就是我需要幫助的地方。 – user1523292 2013-04-29 07:24:18

回答

1

您必須瞭解函數引用和函數調用之間的區別。 .onload屬性預計會分配一個函數引用,但您可以使用函數.onImageLoad的立即(!)調用的返回值分配它。區別在於括號()

如果要調用一個函數參數,回調.onload,那麼你就必須把它列入到一個匿名函數(這本身就是一個函數引用)

frames[i].onload = function() {onImageLoad(assets.length);}; 

有了這個,的當然,你創建一個閉包。這意味着在執行時onImageLoad()方法將有權訪問assets.length的當前值(而不是在賦值點處的值)。但在你的情況下,這並沒有什麼區別,因爲assets.length從不改變。

+0

非常感謝!代碼現在正在工作 – user1523292 2013-04-29 07:47:21