Search code examples
javascripthtmlimageloaderpreload

Javascript multiple images loader


I want to make a javascript image loader.

This is what I try :

function ImgLoader() {

   this.imgs_ = {
       0 : {name: "floor", img: new Image()},
       1 : {name: "highlight", img: new Image()},
       2 : {name: "player-north", img: new Image()},
       3 : {name: "player-south", img: new Image()},
       4 : {name: "player-west", img: new Image()},
       5 : {name: "player-east", img: new Image()},
       6 : {name: "food_small", img: new Image()},
       7 : {name: "food_medium", img: new Image()},
       8 : {name: "food_large", img: new Image()},
   };

}

 ImgLoader.prototype.load = function() {

 for (var i = 0; typeof(this.imgs_[i]) != "undefined"; i++)
     this.imgs_[i].img.src = "img/" + this.imgs_[i].name + ".png";
 }

With this method, I have an "array" of my images, and I can work easily later with. But, it appears that sometimes, few images are not fully loaded.

What is the best way to make this kind of loader ?

Thanks !


Okay Šime Vidas said a very good solution ... BUT : We can not be certain that the image is fully loaded !

This is the code :

var imgs = Object.create( null ); // or var imgs = {};

[
   'floor',
   'highlight',
   'player-north',
   'player-south',
   'player-west',
   'player-east',
   'food_small',
   'food_medium',
   'food_large'
].forEach(function ( name ) {
    var img = new Image;
    img.src = 'img/' + name + '.png';
    imgs[ name ] = img;
});

Use is :

imgs.food_small;

But if I check Image complete Property like this

console.log(imgs.food_small.complete);

Sometimes we can seen : false

I think we should wait for an event like 'onload' before load the next image in the forEach


Solution

  • This is how I'd do it:

    var imgs = Object.create( null ); // or var imgs = {};
    
    [
        'floor',
        'highlight',
        'player-north',
        'player-south',
        'player-west',
        'player-east',
        'food_small',
        'food_medium',
        'food_large'
    ].forEach(function ( name ) {
        var img = new Image;
        img.src = 'img/' + name + '.png';
        imgs[ name ] = img;
    });
    

    Now you can retrieve each individual image like so:

    imgs.food_small
    

    For instance:

    ctx.drawImage( imgs.food_small, 0, 0 );