Search code examples
javascriptkineticjs

kineticjs - set position of multiple images on canvas within a loop


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];
}

Solution

  • 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