在画布上绘制多个方块

时间:2016-05-19 16:02:21

标签: javascript object html5-canvas

我想知道为什么我的方块没有画在画布上。我看到了一个与我类似的帖子,但我无法修复我的代码

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

1 个答案:

答案 0 :(得分:1)

你关闭了!

您的代码中存在以下几个问题:

  • 您必须调用startGame()来运行其代码。
  • 您必须将shape定义为对象:var shape={}

&#13;
&#13;
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;
}
&#13;
<canvas id="myCanvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;