Hope Tsai Hope Tsai - 6 months ago 13
Javascript Question

Drawing multiple squares on the canvas

I was wondering why my squares weren't drawing on the canvas. I saw a different post similar to mine, but I couldn't manage to fix my code

var squares = [];
var ctx;
function startGame() {
ctx = document.getElementById("myCanvas").getContext("2d");
squares.push(drawStuff(75, 75, "red", 10, 10));
squares.push(drawStuff(75, 75, "yellow", 50, 60));
squares.push(drawStuff(75, 75, "blue", 10, 220));
for ( i=0;i<squares.length;i++){
ctx.fillStyle = squares[i].color;
ctx.fillRect(squares[i].left,squares[i].top,squares[i].width,squares[i].height);
}
}
function drawStuff(width, height, color, x, y) {
var shape;
shape.left = x;
shape.top = y;
shape.width = width;
shape.height = height;
shape.color = color;
return shape;
}

Answer

You're close!

You have a couple of issues in your code:

  • You must call startGame() to run its code.
  • You must define shape as an object: var shape={}.

var squares = [];
var ctx;
startGame();
function startGame() {
    ctx = document.getElementById("myCanvas").getContext("2d");
    squares.push(drawStuff(75, 75, "red", 10, 10));
    squares.push(drawStuff(75, 75, "yellow", 50, 60));
    squares.push(drawStuff(75, 75, "blue", 10, 220));
    for ( i=0;i<squares.length;i++){
        ctx.fillStyle = squares[i].color;
        ctx.fillRect(squares[i].left,squares[i].top,squares[i].width,squares[i].height);
    }
}
function drawStuff(width, height, color, x, y) {
    var shape={};
    shape.left = x;
    shape.top = y;
    shape.width = width;
    shape.height = height;
    shape.color = color;
    return shape;
}
<canvas id="myCanvas" width=300 height=300></canvas>