在继续之前等待图像加载 [英] Wait for image to be loaded before going on

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

问题描述

我正在使用 JavaScript 和 canvas 开发游戏.随着游戏加载,将缓存所有将使用的图像.

I'm developing a game using JavaScript and canvas. As the game loads, all images that will be used are being cached.

观察资源时间线,看​​到如下代码触发了一个异步请求:

Observing the resource timeline, I see that the following code triggers an asynchronous request:

var sprite = new Image();
sprite.src = "sprites/sheet1.png";

引擎将继续执行,最终开始绘制和播放关卡.在绘制第一帧后加载的图像可能永远不会出现,因为剪裁(即没有变得脏").

The engine will keep executing, eventually beginning to draw and play the level. Images that are loaded after the first frame is painted might never appear due to clipping (i.e. not getting "dirty").

所以我测试了以下内容:

So I tested the following:

console.log("begin");
var sprite = new Image();
sprite.onload = function() { console.log('loaded!'); };
sprite.src = "sprites/sheet1.png";
console.log("end");

结果控制台输出按它们出现的顺序是:

The resulting console outputs in the order they occur are:

  • 开始
  • end
  • 已加载!

我正在寻找一种类似于 $.ajaxasync: false 的方法来执行加载.无法弄清楚如何......提前感谢您的帮助!J.

I'm looking for a similar way to $.ajax with async: false to perform the loading. Can't figure out how... thanks in advance for you help! J.

推荐答案

你不应该进行任何同步(甚至 AJAX)调用,而只是将你的代码放在适当的回调中:

You shouldn't make anything synchronous (not even AJAX) calls but instead simply put your code in the appropriate callback:

function loadSprite(src, callback) {
    var sprite = new Image();
    sprite.onload = callback;
    sprite.src = src;
}

然后像这样使用它:

loadSprite('sprites/sheet1.png', function() {
    // code to be executed later
});

如果你想传递额外的参数,你可以这样做:

If you want to pass additional arguments, you can do it like this:

sprite.onload = function() {
    callback(whatever, args, you, have);
};

<小时>

如果要加载多个元素并需要等待所有元素完成,请考虑使用 jQuery 延迟 对象:

function loadSprite(src) {
    var deferred = $.Deferred();
    var sprite = new Image();
    sprite.onload = function() {
        deferred.resolve();
    };
    sprite.src = src;
    return deferred.promise();
}

在加载精灵的函数中,你做这样的事情:

In the function loading the sprites, you do something like this:

var loaders = [];
loaders.push(loadSprite('1.png'));
loaders.push(loadSprite('2.png'));
loaders.push(loadSprite('3.png'));
$.when.apply(null, loaders).done(function() {
    // callback when everything was loaded
});

http://api.jquery.com/jQuery.when/

这篇关于在继续之前等待图像加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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