Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - Check if Images are loaded before 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. Should I check if playerImg is loaded first, even though it works correctly so far?

  2. 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?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Handling multiple images

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();
}

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...