将对象添加到数组中

时间:2018-08-09 15:20:10

标签: javascript canvas

有人可以告诉我这段代码有什么问题吗?我试图用正方形作为对象填充画布,但是随着循环的完成,我试图在画布上绘制该正方形,没有任何反应...

var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(35, 180, 218)";

var rectHeight = 5;
var rectWidth = 5;

var cells = [];

for (var i = 0; i <= canvas.width/rectWidth; i++) {
    for (var x = 0; x <= canvas.height/rectHeight; x++) {
        cells[i] = {
            posX : i*rectWidth,
            posY : x*rectHeight,
            draw : function() {
                ctx.fillRect(posX, posY, rectWidth, rectHeight);
            },
            clear : function() {
                ctx.clearRect(posX, posY, rectWidth, rectHeight);
            }
        };
    }
}

cells[2].draw;

2 个答案:

答案 0 :(得分:1)

var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";

var rectHeight = 15;
var rectWidth = 15;

var cells = [];

for (var i = 0; i <= canvas.width/rectWidth; i++) {
    for (var x = 0; x <= canvas.height/rectHeight; x++) {
        cells[i] = {
            posX : i*rectWidth,
            posY : x*rectHeight,
            draw : function() {
                ctx.fillRect(this.posX, this.posY, rectWidth, rectHeight);
            },
            clear : function() {
                ctx.clearRect(positionX, positionY, rectWidth, rectHeight);
            }
        };
    }
}
cells[2].draw();
<canvas id="c" width="500" height="400"></canvas>

答案 1 :(得分:0)

感谢@Xufox @SimranjitSingh和@Andreas的帮助。

代码现在如下所示:

var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(35, 180, 218)";

var rectHeight = 5;
var rectWidth = 5;

var cells = [];

for (var i = 0; i <= canvas.width/rectWidth; i++) {
    for (var x = 0; x <= canvas.height/rectHeight; x++) {
        cells[i*x] = {
            posX : i*rectWidth,
            posY : x*rectHeight,
            draw : function() {
                ctx.fillRect(this.posX, this.posY, rectWidth, rectHeight);
            },
            clear : function() {
                ctx.clearRect(this.posX, this.posY, rectWidth, rectHeight);
            }
        };
    }
}

cells[2].draw();