首页 > 解决方案 > 将对象添加到数组中

问题描述

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

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;

标签: javascriptcanvas

解决方案


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>


推荐阅读