0

How can I set positions of multiple images on canvas within a loop? The following seems to work with:

for (var i=1; i<10; i++) {
  images[i]=new Image();
  images[i].onload = function() {
    drawImage(this, 1, 1, i*50, 700, "bulb"+i);
    // THE POSITION CANNOT BE SET ; i IS ALWAYS 500
  }
  images[i].src = folder+src[i];
}
VividD
  • 10,456
  • 6
  • 64
  • 111

1 Answers1

2

In your example, i has closure outside the function, so its value is tied to what it is at the end of your loop.

You can fix it like this:

for (var i=1; i<10; i++) {
  images[i]=new Image();
  images[i].onload = (function(x) {
    return function () {
      drawImage(this, 1, 1, x*50, 700, "bulb"+x);
    };
  }(i));
  images[i].src = folder+src[i];
}

This makes a new closure for each onload function, assigning it to x each loop iteration.

As a note, this is a rather common JavaScript error

Krease
  • 15,805
  • 8
  • 54
  • 86
  • Is there any chance to thank you for the hint in another way? It solved my problem!! – user3027613 Nov 24 '13 at 16:59
  • Accepting answers that solve your problem (see the check mark beside the question) is the way to do that around these parts :) – Krease Nov 24 '13 at 17:01