Hi everyone and Happy New Year,
I'm working on a small game project using JavaScript and I encountered a problem when loading images.
I want all the images to be loaded before I display them so I created a map in which each image is linked to false, and when the image is loaded, an event listener calls a function which set the image to true in my map.
But sometimes, my map is full of true without any image on my screen and when I print img.complete it's false, meaning it's not loaded.
Everything here is in a class of my file and this.chargementImg is the map.
Here is the image loading function:
chargerImage(chemin)
{
let img = new Image();
this.chargementImg.set(chemin, false);
img.addEventListener("load", this.updateChargementImg(chemin));
img.src = chemin;
return img;
}
And the callback function:
updateChargementImg(chemin)
{
this.chargementImg.set(chemin, true);
}
Console output when no images shown:
Map(3) {'./elements/images/fonds/sol/DarkSpace.png' => true,
'./elements/images/fonds/mur/Castle2.png' => true,
'./elements/images/ennemies/Earthspirit.png' => true}
img1.complete : false
img2.complete : false
img3.complete : false
I don't understand why it's not working. Thanks for your answers.
Make the load EventListener an unnamed function. Inside that put the updateChargementImg and return img. There will then be no race or async.
img.addEventListener("load", function(){
this.updateChargementImg(chemin);
return img;
});
img.src = chemin;