我有我的数组,我想基于数组中每个对象内的whats显示数组。我在这里有循环,但我似乎可以使ctx.fillRect
起作用。
var c = document.getElementById("can");
var ctx = c.getContext("2d");
var blocks = [];
var rows = [0, 1, 2, 3];
function Block(h, w, x, y, c) {
this.h = h;
this.w = w;
this.x = x;
this.y = y;
this.c = c;
}
ctx.fillRect(900, 400, 10, 10)
for (var i = 0, len = rows.length; i < len; i++) {
for (var j = 0; j < 10; j++)
blocks.push(new Block(10, 20, j * 30, i * 30, rows[i]))
}
function draw() {
ctx.fillStyle = "black";
for (var i = 0, len = blocks.length; i < len; i++) {
for (var j = 0, len2 = blocks[i].length; j < len2; j++) {
ctx.fillRect(blocks[i][j].x, blocks[i][j].y, blocks[i][j].w, blocks[i][j].h);
}
}
}
setInterval(draw, 1000);
&#13;
<canvas id="can" height="500" width="1000"></canvas>
&#13;
答案 0 :(得分:5)
blocks
不是多维数组。
var c = document.getElementById("can");
var ctx = c.getContext("2d");
var blocks = [];
var rows = [0, 1, 2, 3];
function Block(h, w, x, y, c) {
this.h = h;
this.w = w;
this.x = x;
this.y = y;
this.c = c;
}
for (var i = 0, len = rows.length; i < len; i++) {
for (var j = 0; j < 10; j++)
blocks.push(new Block(10, 20, j * 30, i * 30, rows[i]))
}
function draw() {
ctx.fillStyle = "#000000";
for (var i = 0, len = blocks.length; i < len; i++) {
ctx.fillRect(blocks[i].x, blocks[i].y, blocks[i].w, blocks[i].h);
}
}
setInterval(draw, 1000);
<canvas id="can" height="500" width="1000"></canvas>