Check if images are loaded before playing gameloop

So far my program works the way I want it. This works great:

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

      

  • Should I check if loaded playerImg

    first even if it works correctly so far?

  • Also, the best way to check. I was thinking about placing all images in an array. Then check the function onLoad

    . If they are all loaded, I will start the game loop. Is this a good idea?

thank

+2


source to share


1 answer


How image loading works

You need to check if the image is loaded as the image loading is asynchronous. You may find that your code works sometimes without it. This is mainly due to the fact that your image exists in the cache and the browser can load it fast enough before being called drawImage

or the image exists on the local disk.

However, new users will need to download the data first, and you don't want early adopters to have errors like images not showing because they haven't been uploaded.

Since it runs asynchronously, your code will continue to execute while the image is loading in the background. This can cause your code to be executed before the image has finished loading. Therefore, image processing is important.

Multiple image processing

You can load all of your images first (or the ones you need to get started) and you can define them using an array:

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

      



Then iterate and create 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 counting inventory:

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

      

The callback is the code you want to execute next. Your images will be in the array images

in the same order as imageURLs

.

For production, you must also enable a handler onerror

in case something goes wrong.

+6


source







All Articles