2017-04-11 66 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