如何加载多张图像的最后一张图像时如何调用函数?

时间:2015-09-09 11:33:22

标签: javascript html5 html5-canvas

我想在加载所有特定图像集时调用函数。目前我只是使用.onload作为最后一张图片,它在99%的时间内都有效,但有时会出现问题。最好的方法是什么?我意识到我可以为每个图像创建一个.onload,然后检查函数内部是否已经加载了所有其他图像,但我觉得必须有一个更有效的方法。

这是我的代码:

P1LCImage.src = "images/" + P1LC + "-card.png";
P1RCImage.src = "images/" + P1RC + "-card.png";
P2LCImage.src = "images/" + P2LC + "-card.png";
P2RCImage.src = "images/" + P2RC + "-card.png";
P3LCImage.src = "images/" + P3LC + "-card.png";
P3RCImage.src = "images/" + P3RC + "-card.png";
P4LCImage.src = "images/" + P4LC + "-card.png";
P4RCImage.src = "images/" + P4RC + "-card.png";
P5LCImage.src = "images/" + P5LC + "-card.png";
P5RCImage.src = "images/" + P5RC + "-card.png";
P6LCImage.src = "images/" + P6LC + "-card.png";
P6RCImage.src = "images/" + P6RC + "-card.png";
blankCardImage.src = "images/blank-card.png";
protectedCardImage.src = "images/protected-card.png";
voteCount1.src = "images/voteCount1.png";
voteCount2.src = "images/voteCount2.png";
voteCount3.src = "images/voteCount3.png";
voteCount4.src = "images/voteCount4.png";
voteCount5.src = "images/voteCount5.png";
voteCount6.src = "images/voteCount6.png";
voteCount6.onload = function () {
    drawTable();        
    };

2 个答案:

答案 0 :(得分:3)

您可以为每个图像添加一个onload,并让每个图像增加一个计数器。当计数器达到图像数量时,所有图像都已加载,您调用drawTable()

示例代码:

var numImgs = 6;
var numLoaded = 0;

function imgLoaded() {

if(++numLoaded === numImgs)
  drawTable();        
};

voteCount1.onload = imgLoaded;
voteCount2.onload = imgLoaded;
voteCount3.onload = imgLoaded;
voteCount4.onload = imgLoaded;
voteCount5.onload = imgLoaded;
voteCount6.onload = imgLoaded;

答案 1 :(得分:2)

如果您知道需要显示多少张图片,可以按照以下方法操作:

var counter = 0;
var TOTAL_IMAGES = 20;
function imageOnLoad() {
    if (++counter >= TOTAL_IMAGES) {
        drawTable();
    }
}

当然TOTAL_IMAGES可能是变量,在这种情况下,您可能使用数组长度或类似的东西。我会将事件附加到DOM类上,因此您无需在每个图像上指定onload事件。例如,我们假设图片包含在id为gallery的div中。在这种情况下,您可以这样做:

document.querySelectorAll('#gallery img').forEach(function() {
    this.onclick = imageOnLoad;
});