Well my problem is that I have an object that is analyzed in a for loop and within it a load event is applied to each element to know when the element is loaded, the problem is that the for loop analyzes all the elements but the code inside the eventListener is applied in each iteration to the last element of the object. I just don't understand, I would like an explanation. Thank you!
var lienzo = document.getElementById('juego').getContext('2d');
var imgs = {
mapa:{ load: false, obj: function(){
let obj = new Image();
obj.src = 'img/tile.png';
return obj;
}
},
vaca:{ load: false, obj: function(){
let obj = new Image();
obj.src = 'img/vaca.png';
return obj;
}
},
cerdo:{ load: false, obj: function(){
let obj = new Image();
obj.src = 'img/cerdo.png';
return obj;
}
},
pollo:{ load: false, obj: function(){
let obj = new Image();
obj.src = 'img/pollo.png';
return obj;
}
}
};
var canvas = {
loadImg: function(img){
for (var key in img){
let obj = img[key].obj();
console.log(key); // mapa , vaca, cerdo , pollo
obj.addEventListener('load', function(){
img[key].load = true;
console.log(key); // pollo, pollo, pollo, pollo
dibujar();
}, false);
}
}
}
canvas.loadImg(imgs);
function dibujar(){
if(imgs.mapa.load){
let obj = imgs.mapa.obj();
lienzo.drawImage(obj, 0,0);
}
if(imgs.vaca.load){
let obj = imgs.vaca.obj();
lienzo.drawImage(obj, 80,30);
}
if(imgs.cerdo.load){
let obj = imgs.cerdo.obj();
lienzo.drawImage(obj, 200,50);
}
if(imgs.pollo.load){
let obj = imgs.pollo.obj();
lienzo.drawImage(obj, 250,300);
}
}
<canvas id="juego"></canvas>
You can do it like this:
This is due to the scope of
var
since it is global and does not respect the scope of only its block.If you change the loop from
var
tolet
it works for you example:for (let key in img){
Differences:
With
let
:Since I
let
exist only inside the loop and since function load is inside it you can see it limiting itself to the loop block changed only the value inside its block by passing a reference of its current value to obj, but not overwriting it.With
var
:Since
var
being global does not limit its scope and exists not only within the loop but also outside and even within the anonymous function, overwriting itself global for each iteration.