0

I am trying to initialise an array of Image() objects, with each having a different x position. However all the objects in the array seems to end up with the same x position. I have tried searching for a solution and it seems that it is related to 'closure' however I am not sure how to fix it.

This is my code:

function initPieces(){
  for (var i = 0; i<8; i++) {
    var piece = new Image();

    piece.x = 5 + i*50;
    piece.y = 5;

    piece.src = "images/piece.png";

    piecesArray.push(piece);

    alert(i + ", " + piecesArray[i].x);
  }
}

I have even tried initialising the piecesArray without a loop by manually declaring a new Image() and setting the x position manually for each of the 8 pieces. However it gives me the same problem.

Anyone's help finding a solution will be greatly appreciated.

codefi
  • 406
  • 1
  • 6
  • 17

2 Answers2

3

I couldn't find a definitive reference for the HTMLImageElement.x and HTMLImageElement.y properties (because that's what you are creating with new Image()), but MDN says they are read-only and experimental, not to be used in production code.

And they are indeed read-only: in a quick test I did they could be set, but reading the value afterwards simply produces 0.

If you want to move the elements around in the page after they have been inserted into the DOM, use standard techniques such as manipulating piece.style.top.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Thank you for the explanation, it explains perfectly why my code does not work. However it's my fault for not mentioning it is used in an HTML5 context, so I have accepted the other answer. – codefi Aug 27 '14 at 13:31
1

You have not yet added those Images to the DOM and so the x, y, offsetLeft, and offsetTop properties have no context (default to zer0).

Either add image to the DOM first before manipulating those, or use a different property:

var piecesArray = [];
function initPieces(){
  for (var i = 0; i<8; i++) {
    var piece = new Image();

    piece.tempX = (i*50 + 5); // temporary place holder for X
    piece.y= 5; // this will not work; allows set, but does not change value

    piece.src = "images/piece.png";

    piecesArray.push(piece);

      alert(i + ": " + piecesArray[i].tempX);
  }
}
initPieces();

See a demo Fiddle here: http://jsfiddle.net/87xff3fy/1/

A reference for Image.x: http://help.dottoro.com/ljkvjhbq.php (don't use it! Use style or a temporary variable that will set the style.top and style.left at render-time)

nothingisnecessary
  • 6,099
  • 36
  • 60
  • Using `tempX` is the solution for my case because I am using it in an HTML5 canvas, so I am not sure if `style.top` is useful because the images are not in the DOM. Thank you! – codefi Aug 27 '14 at 13:29