加载数组中的所有图像后,如何使Javascript事件触发? [英] How can I make a Javascript event to trigger after all images in an array are loaded?

查看:51
本文介绍了加载数组中的所有图像后,如何使Javascript事件触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发HTML5 Canvas游戏,并且该关卡需要预加载一些图像(最终还要加载其他数据,例如音频文件).我打算将所有这些图像存储在数组或容器对象中.我需要做的是找到一种方法,等待所有这些图像完全下载后再继续游戏.

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.

我可以使用jQuery,但我更喜欢使用直接的Javascript代码.window.onload函数在这里是否可以正常工作,因为页面加载时实际上并没有发生?如果不存在此类事件,是否有办法遍历图像对象并检查它们是否已加载?

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?

推荐答案

如果所有图像都已加载(或失败),则可以有一个计数器来检查onload事件.
类似

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
}

这篇关于加载数组中的所有图像后,如何使Javascript事件触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆