I am having no luck creating and accessing an array of objects. I'm trying to draw 10 random rectangles on a canvas and store their X,Y, Width and Height in an array to access later.
var square = {cX : 0, cY : 0, W : 200, H : 100}
var squares = [];
var squaresToMake = 10;
for ( var loopy = 0; loopy < squaresToMake; loopy++ ) {
square.cX = Math.floor(Math.random() * 20);
square.cY = Math.floor(Math.random() * 20);
square.W = Math.floor(Math.random() * 200);
square.H = Math.floor(Math.random() * 50);
squares.push(square);
}
var arrayLength = squares.length;
for (var loopy = 0; loopy < arrayLength; loopy++) {
ctx.rect(squares[loopy].cX, squares[loopy].cY, squares[loopy].W, squares[loopy].H);
ctx.fill();
}
The result I'm getting is the squares array is full of 10 objects that all have the same values: the last values that were generated from loop that assigns random numbers. Please advise me what I'm doing wrong! Thank you