填充所有imageData变量后,调用render()的最佳方法是什么?
我只是使用回调来调用它们,并调用render,还是有更好的方法?
function loadImageData()
{
//Get Background Image Data
var backgroundImg = loadImage(background, function(){
backgroundData = getDataFromImage(backgroundImg);
});
//Get Overlay Image Data
var overlayImg = loadImage(overlay, function(){
overlayData = getDataFromImage(overlayImg);
});
//Get more Image Data
//Get more Image Data
//Get more Image Data
}
function render()
{
ctx.putImageData(backgroundData, 0,0);
}
答案 0 :(得分:1)
从回调内部,将各个图像元素“渲染”到画布上。
var backgroundImg = loadImage(background, function(){
backgroundData = getDataFromImage(backgroundImg);
ctx.putImageData(backgroundData, 0,0);
});
答案 1 :(得分:0)
我的方法包括创建一个你需要的回调数量的“计数器”,如下所示:
function loadImageData()
{
var counter = 5;
function imageReceived() {
if (--counter == 0) render();
}
//Get Background Image Data
var backgroundImg = loadImage(background, function(){
backgroundData = getDataFromImage(backgroundImg);
imageReceived();
});
//Get Overlay Image Data
var overlayImg = loadImage(overlay, function(){
overlayData = getDataFromImage(overlayImg);
imageReceived();
});
//Get more Image Data
//Get more Image Data
//Get more Image Data
当然,我可能会以这样的方式重写它:loadImage()
函数中等待请求的数量增加,并且只要等待的请求数量回到0,就会触发全局回调