javascript - 将对象添加到数组中
问题描述
有人可以告诉我这段代码有什么问题吗?我正在尝试用正方形作为对象填充画布,但是当循环完成并且我试图在画布上绘制那个正方形时,没有任何反应......
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>
推荐阅读
- nosql - RavenDB 替代以减少预算
- arrays - Mongoose Model, cleaning/parsing an Array efficiently
- cmake - What is the proper way to document a CMake module?
- c# - Creating a Visual Studio menu command to get current active file path
- php - 如何在 Bootstrap Modal 中传递 GET 变量?
- html - 三个具有自动宽度的 div 与最宽的 div 一样宽,使每个 div 与其内容一样宽
- c# - AlwaysEncrypted 插入间歇性失败
- unity3d - Unity ScriptableObject 加载行为
- json - 如何在 JSON 响应中拆分参数的多个值?
- fortran - 派生类型的过程中的动态内存释放