To create a grid overlay that allows your game to determine which grid cell was clicked, you can generate separate DOM elements for each cell aligned with the grid dimensions. Using CSS, define styling rules for each grid cell and use the ":hover" selector for hover effects:
/* Styling for each tile in grid with absolute
position against relative wrapper */
.gameAreaWrapper a {
display: block;
position: absolute;
width: 10%;
height: 10%;
}
/* Hover effect to highlight cell on mouseover */
.gameAreaWrapper a:hover {
background: rgba(255, 255, 0, 0.5);
}
A JavaScript function with nested loops can then be used to populate cells for a 10x10 grid like this:
function generateGameBoardSquares(wrapper) {
for (let x = 0; x < 10; x++) {
for (let y = 0; y < 10; y++) {
const cell = document.createElement("a");
cell.style.left = `${x * 10}%`;
cell.style.top = `${y * 10}%`;
wrapper.append(cell);
}
}
}
Below is a complete demo showcasing these concepts:
/* Helper function to generate square grid within a given wrapper */
function generateGameBoardSquares(wrapper) {
function onClick(x, y) {
alert(`You clicked ${x}, ${y}`);
}
for (let x = 0; x < 10; x++) {
for (let y = 0; y < 10; y++) {
const tile = document.createElement("a");
tile.style.left = `${x * 10}%`;
tile.style.top = `${y * 10}%`;
tile.addEventListener("click", () => onClick(x, y));
wrapper.append(tile);
}
}
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 480;
this.canvas.style.cursor = "default";
this.context = this.canvas.getContext("2d");
const gameAreaWrapper = document.querySelector(".gameAreaWrapper");
gameAreaWrapper.append(this.canvas);
gameAreaWrapper.style.width = `${this.canvas.width}px`;
gameAreaWrapper.style.height = `${this.canvas.height}px`;
generateGameBoardSquares(gameAreaWrapper);
this.frameNo = 0;
window.addEventListener('click', function(e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
}
}
myGameArea.start()
/* Highlight grid boundary */
canvas {
background: rgba(255, 0, 0, 0.1);
}
/* Wrapper style for positioning grid cells */
.gameAreaWrapper {
position: relative;
}
/* Styling for each grid cell with absolute positioning */
.gameAreaWrapper a {
display: block;
position: absolute;
width: 10%;
height: 10%;
}
/* Hover effect for grid cells */
.gameAreaWrapper a:hover {
background: rgba(255, 255, 0, 0.5);
}
<div class="gameAreaWrapper">
<!--
Canvas and grid populated by script
<canvas />
-->
</div>
I hope this explanation helps!