2017-04-11 56 views
0

因此,我必須加載一些圖像,我使用承諾來做到這一點,但它似乎並沒有工作,因爲圖像沒有繪製到畫布(我只希望看到最後的圖像,因爲座標是相同的,但仍然)。 但是,如果我使用良好的OL'onload事件,一切正常。context.drawImage()沒有與承諾的圖像一起工作

下面的代碼,加載圖像:

document.addEventListener("DOMContentLoaded", function(){ 
    canvas=document.getElementById("canvas"); 

    var blockNames=[0, 1, 2, 3, 4, 5, 6].map(function(e){ 
     return "assets/block"+e+".png"; 
    }); //create an array with paths here 

    Promise.all(blockNames.map(function(e){ 
     return res.loadImage(e); 
    })).then(function(result){ //when every promise is fulfilled, draw the current image onto the canvas 
     result.map(function(e){ 
      var context=canvas.getContext("2d"); 
      context.drawImage(e, 20, 20); 
     }); 
    }).catch(function(err){ 
     console.log("error: "+err); 
    }); 
}); 

而這裏的res.loadImage(...)功能(我使用browserify):

var loadImage=function(path){ 
    return new Promise(function(resolve, reject){ 
     var img=new Image(); 
     img.onload=resolve.call(null, img); 
     img.onerror=reject.call(null, img); 
     img.src=path; 
    }); 
}; 

回答

0

的決心功能立即調用它,將其包裝在一個函數中:

img.onload = function() { 
    resolve.call(null, img); 
}; 

img.onerror = function() { 
    reject.call(null, img); 
}; 
+0

哦,對了,謝謝!我錯誤地呼籲綁定。 – skyfire2008