下面是创建一个随机填充白色/黑色方块的6x6网格的代码。当您单击一个正方形时,在控制台中它会显示给定方阵列中的位置。我正在努力的是一旦你点击一个正方形就让它翻转颜色(例如,当你点击一个白色方块,它变成黑色等)。更改也应更新数组,因为最后我将检查结果模式是否具有对称线。
// Create canvas
var canvas = document.getElementById('canvas');
ctx = canvas.getContext("2d");
var canvasCreate = function(w, h) {
canvas.width = w;
canvas.height = h;
};
function resetCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGrid(genArray(6));
}
// Generate a 6x6 array of 0s or 1s
function genArray(aSize) {
a = new Array();
for (var i=0;i<aSize;i++) {
a[i] = new Array();
for (var j=0;j<aSize;j++) {
a[i][j] = Math.floor(Math.random() * 2);
}
}
return a
}
function drawGrid(arr) {
var n = 6;
for (var i=0;i<n;i++) {
for (var j=0;j<n;j++) {
ctx.beginPath();
ctx.strokeStyle = '#555';
if (arr[i][j] === 1) {
ctx.fillRect(i*50, j*50, 50, 50);
}
ctx.rect(i * 50, j * 50, 50, 50);
ctx.stroke();
}
}
// Get mouse position within canvas
function mouseClick(e) {
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
var gridX = Math.floor(mouseX / 50);
var gridY = Math.floor(mouseY / 50);
console.log(gridX, gridY);
var xy = arr[gridX][gridY];
if (xy == 0) {
xy = 1;
console.log("white");
}
else if (xy == 1) {
xy = 0;
console.log("black");
}
//
}
canvas.addEventListener('mousedown', mouseClick, false);
};
arr = genArray(6);
canvasCreate(300, 300);
drawGrid(arr);
...和相应的html:
<button onclick="resetCanvas()">Reset</button>
<canvas id="canvas"></canvas>
编辑:显示我尝试过的内容:
var xy = arr[gridX][gridY];
if (xy == 0) {
xy = 1;
console.log("white");
drawGrid(arr);
}
else if (xy == 1) {
xy = 0;
console.log("black");
drawGrid(arr);
}
如上所示,数组中的位置被识别(例如,(0,3)),然后值在0和1之间变化,整个网格应重新绘制。它改变了一些方块的颜色,但不是我想要的方式。此外(点击几下后,它似乎扼杀了一个浏览器,表明我做错了。
编辑2:根据以下评论,我已将其更新为:
var xy = arr[gridX][gridY];
if (xy == 0) {
arr[gridX][gridY] = 1;
console.log("white");
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGrid(arr);
}
else if (xy == 1) {
arr[gridX][gridY] = 0;
console.log("black");
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGrid(arr);
}
仍然出现故障并导致浏览器无法响应。