Tony Tony - 1 year ago 62
Javascript Question

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
    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
    function. If they are all loaded then I will start the game loop. Is this a good idea?


Answer Source

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

    /// 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
    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.