gpt4 book ai didi

javascript - 将对象添加到数组中

转载 作者:行者123 更新时间:2023-12-03 01:20:55 26 4
gpt4 key购买 nike

有人能告诉我这段代码有什么问题吗?我试图用正方形作为对象填充 Canvas ,但是当循环完成并且我试图在 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;

最佳答案

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>

关于javascript - 将对象添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51770693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com