I have implemented an isometric grid in HTML canvas.
My goal is to handle mouse hover events on the buildings within the grid.
Some buildings will vary in heights.
In the image below, you can see that when hovering over a tile, the highlighted area shifts if the mouse pointer is not directly on the ground tile or is positioned within the building image itself.
I am looking for a solution to enable clicking on each individual building. How can this issue be resolved?
Main basic functions:
let applied_map = ref([]); // tileMap
let tile_images = ref([]); // contains loaded images for canvas consumption
let tile_height = ref(50);
let tile_width = ref(100);
const renderTiles = (x, y) => {
// code block for rendering tiles
};
const renderTileBackground = (x, y, width, height) => {
// function implementation for rendering tile backgrounds
};
const renderTexturedTile = (imgSrc, x, y, tileHeight) => {
// function implementation for rendering textured tiles
};
const renderTileHover = (x, y, width, height) => {
// function implementation for rendering hover effect on tiles
};
https://i.sstatic.net/ZWbNy.png
Updates after answer below
After following Helder Sepulveda's suggestion, I created a new function called drawCube.
This function has been integrated into my click functionality and the renderTiles method. It generates a cube with three faces, aligning it with the position of the building and storing the path for global reference. The cube adjusts its position based on the isometric grid layout.
https://i.sstatic.net/Y2IGt.jpg https://i.sstatic.net/b1kj0.jpg
//...some code within click function
//...
if (tile_images.value[tileIndex] !== undefined) {
drawCube(
hoverTileX.value + tile_height.value,
hoverTileY.value +
Number(tile_images.value[tileIndex].img.height / 2) -
10,
tile_height.value,
tile_height.value,
Number(tile_images.value[tileIndex].img.height / 2),
ctx.value,
{
tile_index: tileIndex - 1 < 0 ? 0 : tileIndex - 1,
}
);
}
This is the drawCube function:
const drawCube = (x, y, wx, wy, h, the_ctx, options = {}) => {
// function definition for drawing a cube
};