You can add event listeners to detect mouse clicks on the canvas and determine which cell was clicked. When a cell is clicked, you will change its color to blue. Here's how you can modify your code to achieve this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Strategy Because Why not?</title>
</head>
<style>
#canvas {
border: 3px solid black;
}
body {
background-color: #4a4a4a;
}
</style>
<body>
<canvas id="canvas" width="800px" height="800px"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const cellSize = 50;
const rows = 16;
const cols = 16;
let cells = [];
// Cell class
class Cell {
constructor(color, x, y) {
this.color = color;
this.x = x;
this.y = y;
}
drawRect() {
ctx.strokeStyle = "black";
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, cellSize, cellSize);
ctx.strokeRect(this.x, this.y, cellSize, cellSize);
}
isClicked(mx, my) {
return mx >= this.x && mx <= this.x + cellSize && my >= this.y && my <= this.y + cellSize;
}
}
// Create cells
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
cells.push(new Cell("green", i * cellSize, j * cellSize));
cells[cells.length - 1].drawRect();
}
}
// Handle canvas click
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const mx = event.clientX - rect.left;
const my = event.clientY - rect.top;
for (let cell of cells) {
if (cell.isClicked(mx, my)) {
cell.color = "blue"; // Change color to blue
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
for (let drawCell of cells) {
drawCell.drawRect(); // Redraw all cells
}
break;
}
}
});
</script>
</body>
</html>
Explanation of Changes:
-
Cell Array:
- We store each cell instance in a
cells array to manage them collectively.
-
Mouse Click Detection:
- An event listener is added to the canvas to respond to click events.
- The mouse's x and y coordinates are calculated relative to the canvas position.
-
Checking for Clicks on Cells:
- A new method
isClicked(mx, my) was added to the Cell class to check if the mouse click occurred within the boundaries of a cell.
-
Change Color and Redraw:
- If a cell is clicked, its color changes to blue, and the canvas is cleared and redrawn to reflect the color change.
This setup will allow you to click on the green cells, and they will turn blue when clicked.