Why won\'t my multiple rectangles draw in the canvas?
Ok, so you were almost there.
When you iterate round your array of rectangles, you are iterating over the array key not the objects themselves (see How to Loop through plain JavaScript object with objects as members?).
Plus, as @jimjimmy1995 pointed out, you need to set the fill using .fillStyle
as .fillRect
does not have a fill parameter.
This code will work:
function Shape(x, y, w, h, fill) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
// get canvas element.
var elem = document.getElementById('myCanvas');
// check if context exist
if (elem.getContext) {
var myRect = [];
myRect.push(new Shape(10, 0, 25, 25, "#333"));
myRect.push(new Shape(0, 40, 39, 25, "#333"));
myRect.push(new Shape(0, 80, 100, 25, "#333"));
context = elem.getContext('2d');
for (var i in myRect) {
oRec = myRect[i];
context.fillStyle = oRec.fill;
context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
}
}
Don't you need to give it the fill color?
context.fillStyle = i.fill;
context.fillRect(i.x,i.y,i.w,i.h);