我想知道为什么我的方块没有画在画布上。我看到了一个与我类似的帖子,但我无法修复我的代码
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;
}
答案 0 :(得分:1)
你关闭了!
您的代码中存在以下几个问题:
shape
定义为对象: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;
}
&#13;
<canvas id="myCanvas" width=300 height=300></canvas>
&#13;