The following code snippet is intended to loop through the array (which contains 4 objects); with each iteration it is supposed to produce the image of a card. After 4 iterations, there should be 4 cards side by each in a row.
Problem: only the final image shows up (i.e. the element of myHeroCards[3].image). The alert box shows, in sequence, with each iteration: "0","1",2".
Related posts refer to problems with using "for loops" to step though an array; but I don't think that's the problem because I can get any given image to show up by replacing x
with a value of 0-3.
I suspect an interaction with how onload works and how the loop statements are evaluated, but I'm stumped on the details.
function startingCardLayout(){
var nextHeroCard=0;
var x=0;
for (i=0;i<=2;i++){
myHeroCards[x].image.onload = function (){ctx.drawImage(myHeroCards[x].image,(xFirstCol+(x*xColInc)),100,xCardSize,yCardSize);}
alert(x);
x=x+1;
}
}