运行时,它会显示
未捕获的TypeError:无法读取未定义的属性“ 0”。
我不知道如何解决这个问题。
画布:<canvas id="c" style="background-color: black;">
var c = document.getElementById('c');
var ctx = c.getContext('2d');
c.width = window.innerWidth;
c.height = window.innerHeight;
var grid = [];
for (var j = 0; j < c.height; j++) {
grid.push([]);
for (var i = 0; i < c.width; i++) {
grid[j].push(0);
}
}
function draw() {
ctx.clearRect(0, 0, c.width, c.height);
for (var j = 0; j < grid.length; j++) {
for (var i = 0; i < grid[0].length; i++) {
ctx.fillStyle = (grid[i][j] == 0) ? 'red' : 'blue';
ctx.fillRect(i, j, 1, 1);
}
}
}
//setInterval(draw, 10);
draw();
<canvas id="c" style="background-color: black;">
答案 0 :(得分:0)
您应该在内部for循环中添加grid.length
而不是grid[0].length
。
var c = document.getElementById('c');
var ctx = c.getContext('2d');
c.width = window.innerWidth;
c.height = window.innerHeight;
var grid = [];
for (var j = 0; j < c.height; j++) {
grid.push([]);
for (var i = 0; i < c.width; i++) {
grid[j].push(0);
}
}
function draw() {
ctx.clearRect(0, 0, c.width, c.height);
for (var j = 0; j < grid.length; j++) {
for (var i = 0; i < grid.length; i++) {
ctx.fillStyle = (grid[i][j] == 0) ? 'red' : 'blue';
ctx.fillRect(i, j, 1, 1);
}
}
}
//setInterval(draw, 10);
draw();
<canvas id="c" style="background-color: black;">