Below is the code to create a 6x6 grid that is randomly populated with white/black squares. At the moment when you click on a square, in console it displays the position of within an array of a given square. What I am struggling with is to make it flip the color once you click on a square (eg. when you click on a white square, it becomes black, etc.). The change should also update the array as in the end I will be checking whether the resulting patter has a line of symmetry.
// 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);
... and corresponding html:
<button onclick="resetCanvas()">Reset</button>
<canvas id="canvas"></canvas>
Edit: to show what I've tried:
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);
}
As you can see above, the position in the array is identified (eg. (0, 3)), then the value gets changed between 0 and 1 and the whole grid should get redrawn. It changes the colors of some squares, but not in a way I intended. Additionally (after a few clicks, it seems to choke a browser indicating that I'm doing something wrong.
Edit 2: Upon the comment below I've updated it to:
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);
}
Still it malfunctions and gets the browser not responsive.