Update after code was provided
With your code you are setting a color and then drawing it without storing that information. My recommendation would be to restructure your code so that each cell is an object with values if you want to manipulate them afterwards. If you want a quick fix I would index random colors to each cell. One more option would be to get the color value from a pixel in each cell. Example provided in this post: Get pixel color from canvas
Normally when you make a for loop you will increase the count by 1. Your code would be easier to work with if you looped from 0 to 9 instead of 0 to 440. But using what you provided you could create an array like the snippet below.
What I do here is create an array containing the 121 (11 by 11) colors. Then when drawing we use an index in the array for each drawing. To modify colors all you have to do is manipulate the array.
As per your original post, you want no squares to be equal to its neighbor. I added this into the setup of the array instead of checking afterwards.
while(arr[i] === arr[i -1] || arr[i] === arr[i -10]) {
arr[i] = randomColor();
}
this makes sure no color is pushed to the array if the color left of itself or top of itself. This code is slow since it can run the randomColor() function many times for every cell.
Original Answer
There are many ways to do what you described. Depending on how you created your table the answer will vary. Some possibilities:
- Each cell could be a javascript object with a
color:
property.
- When creating the random setup just push the colors to an array and fetch each cells color to that of its index in the array.
- There is a way to draw DOM objects on canvas, if this is your approach you could check the objects style property. Likely
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>