我使用 Canvas 构建了一个 10*10 的表格。每个单元格随机着色为绿色、蓝色或红色。现在我想检查表中每个单元格的颜色,如果与其邻居相同则更改它。 如何检查每个单元格的颜色?
var color;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function drawBoard() {
for (let i = 0; i < 440; i += 40) {
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, 400);
context.stroke();
}
for (let i = 0; i < 440; i += 40) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(400, i);
context.stroke();
}
for (let i = 0; i < 440; i += 40) {//row
for (let j = 0; j < 440; j += 40) {//column
let color = randomColor();
context.fillStyle = color;
context.fillRect(j , i , 40, 40);
}
}
}
drawBoard();
function randomColor() {
let colorOptions = ["RED", "BLUE", "GREEN"];
let index = Math.floor(Math.random() * colorOptions.length);
return colorOptions[index];
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas" height="600" width="600"></canvas>
<script src="script.js"></script>
</body>
</html>
最佳答案
提供代码后更新
使用您的代码,您可以设置一种颜色,然后在不存储该信息的情况下绘制它。我的建议是重构您的代码,以便每个单元格都是一个具有值的对象(如果您想随后对其进行操作)。如果您想要快速修复,我将为每个单元格索引随机颜色。另一种选择是从每个单元格中的像素获取颜色值。本文提供的示例:Get pixel color from canvas
通常,当你进行 for 循环时,你会将计数增加 1。如果你从 0 循环到 9 而不是 0 到 440,你的代码会更容易使用。但是使用你提供的内容,你可以创建一个像这样的数组下面的代码片段。
我在这里所做的是创建一个包含 121 种(11 x 11)颜色的数组。然后,在绘图时,我们为每个绘图使用数组中的索引。要修改颜色,您所要做的就是操作数组。
根据您原来的帖子,您不希望任何方 block 与其邻居相等。我将其添加到数组的设置中,而不是事后检查。
while(arr[i] === arr[i -1] || arr[i] === arr[i -10]) {
arr[i] = randomColor();
}
这可以确保如果颜色位于其自身左侧或顶部,则不会将颜色推送到数组中。此代码速度很慢,因为它可以为每个单元格多次运行 randomColor() 函数。
原始答案
有很多方法可以实现您所描述的操作。根据您创建表格的方式,答案会有所不同。一些可能性:
- 每个单元格都可以是一个带有
color:
属性的 JavaScript 对象。 - 创建随机设置时,只需将颜色推送到数组中,然后将每个单元格的颜色提取到数组中索引的颜色即可。
- 有一种方法可以在 Canvas 上绘制 DOM 对象,如果这是您的方法,您可以检查对象样式属性。可能
yourCell.style.background
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
const colorArray = fillArray();
function drawBoard() {
for (let i = 0; i < 440; i += 40) {
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, 400);
context.stroke();
}
for (let i = 0; i < 440; i += 40) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(400, i);
context.stroke();
}
for (let i = 0; i < 440; i += 40) {//row
for (let j = 0; j < 440; j += 40) {//column
context.fillStyle = colorArray[i/4 + j/40];
context.fillRect(j , i , 40, 40);
}
}
}
drawBoard();
function fillArray() {
let arr = [];
for (let i = 0; i < 121; i += 1) {
arr.push(randomColor());
while(arr[i] === arr[i -1] || arr[i] === arr[i -10]) {
arr[i] = randomColor();
}
}
return arr;
}
function randomColor() {
let colorOptions = ["RED", "BLUE", "GREEN"];
let index = Math.floor(Math.random() * colorOptions.length);
return colorOptions[index];
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas" height="600" width="600"></canvas>
<script src="script.js"></script>
</body>
</html>
关于javascript - 检查 Canvas 中表格中的单元格颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51569444/