问题描述
我在画布上绘制了一些矩形,以便制作一个网格。我想要的是在网格中对每个矩形进行逐个着色,直到每个矩形都被着色为黑色,然后再次选择其中几个以相同的方式逐一着色为白色。我尝试使用“ for”循环和“ setTimeout”的几种方法,但无法解决。 我最近开始使用javascript,这就是为什么我需要帮助才能做到这一点。
此代码仅包括网格的制作,因为该部分没有解决:
var canvas;
var ctx;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
tileW = 20;
tileH = 20;
tileRowCount = 25;
tileColCount = 40;
var tile = [];
for (c = 0; c < tileColCount; c++) {
tile[c] = [];
for (r = 0; r < tileRowCount; r++){
tile[c][r] = {
x: c * (tileW + 3),y: r * (tileH + 3),state: 'e'
}; //state e for empty
}
}
for (c = 0; c < tileColCount; c++)
for (r = 0; r < tileRowCount; r++) {
ctx.beginPath();
ctx.fillStyle = '#AAAAAA';
ctx.rect(tile[c][r].x,tile[c][r].y,tileW,tileH);
ctx.closePath();
ctx.fill();
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="canvas" width='1000' height='600'></canvas>
<script type="text/javascript" src='data.js'></script>
</body>
</html>
解决方法
从2d上下文中更新渲染代码以使用fillRect
方法。
替换此:
ctx.beginPath();
ctx.fillStyle = '#AAAAAA';
ctx.rect(tile[c][r].x,tile[c][r].y,tileW,tileH);
ctx.closePath();
ctx.fill();
与此:
ctx.fillStyle = "#AAAAAA";
ctx.fillRect(tile[c][r].x,tileH);
,
不清楚您想要什么。我的猜测是您想要一个棋盘格。下面将这样做。
Remainder运算符
运算符%
在除法后返回remainder。例如3 % 2
为1,而4 % 2
为0
我们可以使用余数运算符让我们知道制作每个正方形的颜色。当我们对行进行递减计数时,行计数的其余部分和2将在0和1之间切换。对于每一列,我们都希望相反。如果将行数添加到列数并获得余数,我们将获得所需的结果。示例(r + c)
将给出(0 + 0) % 2 == 0
,(1 + 0) % 2 == 1
,(2 + 0) % 2 == 0
,(3 + 0) % 2 == 1
,然后是下一列(0 + 1) % 2 == 1
,(1 + 1) % 2 == 0
,{{ 1}},(2 + 1) % 2 == 1
。等等。
(3 + 1) % 2 == 0
运算符的precedence比addition运算符+
高,因此我们需要将grouping运算符(
{{3 }}。
例如%
等于4。首先完成3 + 1 % 2
,然后加3;而1 % 2
等于0。首先完成(3 + 1) % 2
,然后完成余数
)
运算符
我们最简单的方法是使用Ternary运算符ternary。例如(3 + 1)
与color = (c + r) % 2 ? "white" : "black"
示例
if ((c + r) % 2 === 1) { color = "white" } else { color = "black" }
const ctx = canvas.getContext('2d');
const tileW = 20;
const tileH = 20;
const tileRowCount = 25;
const tileColCount = 40;
const tiles = [];
for (let c = 0; c < tileColCount; c++) {
for (let r = 0; r < tileRowCount; r++) {
tiles.push({
x: c * (tileW + 3),y: r * (tileH + 3),color: (c + r) % 2 ? "white" : "black",});
}
}
for (const tile of tiles) {
ctx.fillStyle = tile.color;
ctx.fillRect(tile.x,tile.y,tileH);
}