How can I make a Javascript event to trigger after all images in an array are loaded?

假装没事ソ 提交于 2021-02-08 06:10:58

问题


I am working on an HTML5 Canvas game, and the level needs to pre-load some images (and eventually other data such as audio files, too). I am planning on having all of these images stored in an array, or a container object. What I need to do is find a way to wait until all of these images are downloaded completely before continuing in the game.

This does NOT happen when the page is opened. This happens deep within the running script, and the images are dynamically loaded. The idea is to display a "loading" message, and once everything is done, start the level as intended.

I have access to jQuery, but I would prefer to stick with straight Javascript code. Does the window.onload function work here since it's not actually happening when the page loads? If no such event exists, is there a way to traverse through image objects and check if they're loaded yet?


回答1:


You can have a counter to check in the onload event if all the images load(or failed).
Something like

var loadedImages = 0;
var failedImages = 0;
var imageCount = amount of images
function loaded(){
    loadedImages++;
    if (loadedImages == imageCount){
        //all images successfully loaded
    }
    else if ((loadedImages+failedImages) == imageCount){
        //all images completed
    }
}
function failed(){
    failedImages++;
    if ((loadedImages+failedImages) == imageCount){
        //all images completed
    }
}
var images = array();
for (var i = 0; i < imageCount; i++){
    images[i].onload = loaded;
    images[i].onerror = failed;
    images[i].src = the image source
}



回答2:


I would start from this answer and convert it to work for multiple images. It uses jquery though.



来源:https://stackoverflow.com/questions/11003543/how-can-i-make-a-javascript-event-to-trigger-after-all-images-in-an-array-are-lo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!