检查图像是否在gameloop之前加载

检查图像是否在gameloop之前加载

本文介绍了检查图像是否在gameloop之前加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我的程序正在以我想要的方式工作。这很好:

So far my program is working the way I want it to. This works fine:

// Player object
var player = {
   x: 10,
   y: 10,
   draw: function () {
       ctx.drawImage(playerImg, 0, 0);
   ...




  1. playerImg 首先加载,即使它目前正常工作吗?

  1. Should I check if playerImg is loaded first, even though it works correctly so far?

方式检查。我正在考虑把所有的图像放在一个数组。然后检查 onLoad 函数。如果他们都加载,那么我将开始游戏循环。这是个好主意吗?

Also, what is the best way to check. I was thinking about putting all the images in an array. Then check with the onLoad function. If they are all loaded then I will start the game loop. Is this a good idea?

感谢

推荐答案

图片加载的工作原理



您需要检查图片是否加载,因为图片加载是异步的。你可能会体验到你的代码工作有时没有。这主要是因为您的映像存在于缓存中,浏览器能够在调用 drawImage 之前加载它,或者映像存在于本地磁盘上。

How image loading works

You need to check if the image is loaded as image loading is asynchronous. You may experience that your code works sometimes without. This is mainly because your image exists in the cache and the browser is able to load it fast enough before the drawImage is called, or the image exists on local disk.

但是,新用户需要先下载数据,而不希望第一次使用的用户遇到错误,如由于未完成加载而无法显示图片。

However, new users will need to download the data first and you don't want first-time users to experience errors such as images not showing because they are not finished loading.

由于它的工作方式异步,您的代码将继续执行,而图片加载会在后台进行。这可能会导致您的代码在图像加载完成之前执行。因此处理图片加载很重要

As it works asynchronous your code will continue to execute while the image loading takes place in the background. This may cause your code to execute before the image has finished loading. So handling image loading is important

您可以先加载所有图片需要开始),你可以使用数组定义它们:

You can load all your images first (or those you need to start with) and you can define them using array:

var imageURLs = [url1, url2, url3, ...],
    images = [],
    count = imageURLs.length;

然后迭代并创建图像元素:

Then iterate and create the image elements:

for(var i = 0; i < count; i++) {

    /// create a new image element
    var img = new Image();

    /// element is valid so we can push that to stack
    images.push(img);

    /// set handler and url
    img.onload = onloadHandler;
    img.src = imageURLs[i];

    /// if image is cached IE (surprise!) may not trigger onload
    if (img.complete) onloadHandler().bind(img);
}

,在回调函数中执行清单计数:

and in the callback function do the inventory count:

function onloadHandler() {
    /// optionally: "this" contains current image just loaded
    count--;
    if (count === 0) callbackDone();
}

您的回调是您接下来要执行的代码。您的图片将以与 imageURLs 相同的顺序位于数组图片中。

Your callback is the code you want to execute next. Your images will be in the array images in the same order as the imageURLs.

对于生产,你还应该加入 onerror 处理程序,以防发生错误。

For production you should also incorporate an onerror handler in case something goes wrong.

这篇关于检查图像是否在gameloop之前加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:42