我创建10 * 10数组,我想使用画布用不同的颜色填充2D数组中的每个单元格。我尝试仅使用画布来完成此操作,但在下一阶段,我需要检查每个单元格是否具有与其邻居不同的颜色。 有任何想法吗?
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var cols = 10;
var rows = 10;
var board = [];
function start() {
for (var i = 0; i < cols; i++) {
board[i] = [];
for (let j = 0; j < rows; j++) {
//add code here
}
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas" height="600" width="600"></canvas>
<script src="script.js"></script>
</body>
</html>
答案 0 :(得分:0)
这是一个可行的解决方案:
function genBoard(cols, rows) {
let board = [];
for (let i = 0; i < cols; i++) {
board[i] = [];
for (let j = 0; j < rows; j++) {
[
board[i - 1] && board[i - 1][j] || null,
board[i][j - 1] || null
].reduce((colorA, colorB) => {
do {
board[i][j] = '#' + (Math.random().toString(16) + '0000000').slice(2, 8);
} while (colorA === board[i][j] || colorB === board[i][j])
});
}
}
return board;
}
let colorsBoard = genBoard(5, 5);
console.log(JSON.stringify(colorsBoard));
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
let [x, y, width, height] = [0, 0, 50, 50];
colorsBoard.forEach((row, i) => row.forEach((color, j) => {
[x, y] = [width * j, height * i];
context.moveTo(x, y);
context.fillStyle = color;
context.fillRect(x, y, width, height);
}));
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas" height="600" width="600"></canvas>
<script src="script.js"></script>
</body>
</html>
首先生成您的颜色,然后使用画布进行渲染。
在2d数组中设置每个颜色值时,请检查它是否已经在索引[i - 1, j]
和/或[i, j - 1]
处。如果是这样,请使用do ... while
循环对其进行更改。