htmlcsstooltip

Incorrect position of tooltip on a canvas


I’m trying to click on any of the cells to get a tooltip next to the cell, but I’m having a lot of trouble getting the correct coordinates. I went through it and none of the solutions worked. What could it be?

<style>
    canvas {
        position: relative;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .tooltipMap {
        position: absolute;
        display: none;
        background-color: white;
        border: 1px solid black;
        padding: 5px;
        box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
        border-radius: 5px;
        font-size: 14px;
        z-index: 10;
    }

    .tooltipMap button {
        padding: 5px 10px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 3px;
        cursor: pointer;
    }

    .tooltipMap button:hover {
        background-color: #0056b3;
    }
</style>

<div id="tooltipMap" class="tooltipMap">
    <p>Comprar esta celda</p>
    <button id="buyButton">Comprar</button>
</div>

<canvas id="gameMap" width="1000" height="1000"></canvas>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const canvas = document.getElementById('gameMap');
        const ctx = canvas.getContext('2d');
        const tooltipMap = document.getElementById('tooltipMap');
        const buyButton = document.getElementById('buyButton');

        const img = new Image();
        img.onload = function() {
            ctx.drawImage(img, 0, 0);

            const gridSize = 50;

            function drawGrid() {
                ctx.strokeStyle = '#D3D3D3';
                ctx.setLineDash([5, 5]);
                ctx.lineWidth = 1;

                for (let x = 0; x <= 1000; x += gridSize) {
                    ctx.beginPath();
                    ctx.moveTo(x, 0);
                    ctx.lineTo(x, 1000);
                    ctx.stroke();
                }

                for (let y = 0; y <= 1000; y += gridSize) {
                    ctx.beginPath();
                    ctx.moveTo(0, y);
                    ctx.lineTo(1000, y);
                    ctx.stroke();
                }
            }

            function drawCellNumbers() {
                ctx.setLineDash([]);
                ctx.fillStyle = 'black';
                ctx.strokeStyle = 'white';
                ctx.lineWidth = 3;
                ctx.font = 'bold 18px Arial';
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';

                let cellNumber = 1;
                for (let y = 0; y < 1000; y += gridSize) {
                    for (let x = 0; x < 1000; x += gridSize) {
                        ctx.strokeText(cellNumber, x + gridSize / 2, y + gridSize / 2);
                        ctx.fillText(cellNumber, x + gridSize / 2, y + gridSize / 2);
                        cellNumber++;
                    }
                }
            }

            drawGrid();
            drawCellNumbers();

            let highlightedCell = null;

            function getCellCoords(x, y) {
                return {
                    col: Math.floor(x / gridSize) * gridSize,
                    row: Math.floor(y / gridSize) * gridSize
                };
            }

            function highlightCell(col, row) {
                ctx.strokeStyle = 'black';
                ctx.setLineDash([]);
                ctx.lineWidth = 3;
                ctx.strokeRect(col, row, gridSize, gridSize);
            }

            function redraw() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0);
                drawGrid();
                drawCellNumbers();
            }

            canvas.addEventListener('mousemove', function(event) {
                const rect = canvas.getBoundingClientRect();
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                const mouseX = (event.clientX - rect.left) * scaleX;
                const mouseY = (event.clientY - rect.top) * scaleY;

                const cellCoords = getCellCoords(mouseX, mouseY);

                if (highlightedCell && (highlightedCell.col !== cellCoords.col || highlightedCell.row !== cellCoords.row)) {
                    redraw();
                }

                highlightedCell = cellCoords;
                highlightCell(cellCoords.col, cellCoords.row);
            });

            canvas.addEventListener('click', function(event) {
                const rect = canvas.getBoundingClientRect();
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                const mouseX = (event.clientX - rect.left) * scaleX;
                const mouseY = (event.clientY - rect.top) * scaleY;

                const cellCoords = getCellCoords(mouseX, mouseY);

                const tooltipMapX = cellCoords.col + canvas.offsetLeft;
                const tooltipMapY = cellCoords.row + canvas.offsetTop + gridSize;

                tooltipMap.style.left = `${tooltipMapX}px`;
                tooltipMap.style.top = `${tooltipMapY}px`;
                tooltipMap.style.display = 'block';

                buyButton.onclick = function() {
                    const cellNumber = Math.floor(mouseY / gridSize) * (1000 / gridSize) + Math.floor(mouseX / gridSize) + 1;
                    alert(`Has comprado la celda número ${cellNumber}`);
                    tooltipMap.style.display = 'none'; // Ocultar el tooltipMap tras la compra
                };
            });

            canvas.addEventListener('mouseleave', function() {
                tooltipMap.style.display = 'none';
            });
        };

        img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/000080_Navy_Blue_Square.svg/2048px-000080_Navy_Blue_Square.svg.png';
    });
</script>

If you can see in the example it seems to be a problem of image size and relative positioning, that’s what I imagine but I can’t find the solution.

Also if you know a better way to do the job, I would appreciate it. This seemed to be a pretty simple option until I had this problem with the tooltip.


Solution

  • The problem is that when displaying the tooltip, you are providing scaled coordinates (canvas coordinates), but what you need to provide are unscaled coordinates (page coordinates). Remember that the tooltip is not a child of the canvas, it is a child of the page.

    So the fix is a simple one. Divide by the scale when calculating your tooltip coordinates:

    const tooltipMapX = cellCoords.col / scaleX + canvas.offsetLeft;
    const tooltipMapY = cellCoords.row / scaleY + canvas.offsetTop + gridSize;
    

    A snippet to demonstrate the fix:

        document.addEventListener('DOMContentLoaded', function() {
            const canvas = document.getElementById('gameMap');
            const ctx = canvas.getContext('2d');
            const tooltipMap = document.getElementById('tooltipMap');
            const buyButton = document.getElementById('buyButton');
    
            const img = new Image();
            img.onload = function() {
                ctx.drawImage(img, 0, 0);
    
                const gridSize = 50;
    
                function drawGrid() {
                    ctx.strokeStyle = '#D3D3D3';
                    ctx.setLineDash([5, 5]);
                    ctx.lineWidth = 1;
    
                    for (let x = 0; x <= 1000; x += gridSize) {
                        ctx.beginPath();
                        ctx.moveTo(x, 0);
                        ctx.lineTo(x, 1000);
                        ctx.stroke();
                    }
    
                    for (let y = 0; y <= 1000; y += gridSize) {
                        ctx.beginPath();
                        ctx.moveTo(0, y);
                        ctx.lineTo(1000, y);
                        ctx.stroke();
                    }
                }
    
                function drawCellNumbers() {
                    ctx.setLineDash([]);
                    ctx.fillStyle = 'black';
                    ctx.strokeStyle = 'white';
                    ctx.lineWidth = 3;
                    ctx.font = 'bold 18px Arial';
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
    
                    let cellNumber = 1;
                    for (let y = 0; y < 1000; y += gridSize) {
                        for (let x = 0; x < 1000; x += gridSize) {
                            ctx.strokeText(cellNumber, x + gridSize / 2, y + gridSize / 2);
                            ctx.fillText(cellNumber, x + gridSize / 2, y + gridSize / 2);
                            cellNumber++;
                        }
                    }
                }
    
                drawGrid();
                drawCellNumbers();
    
                let highlightedCell = null;
    
                function getCellCoords(x, y) {
                    return {
                        col: Math.floor(x / gridSize) * gridSize,
                        row: Math.floor(y / gridSize) * gridSize
                    };
                }
    
                function highlightCell(col, row) {
                    ctx.strokeStyle = 'black';
                    ctx.setLineDash([]);
                    ctx.lineWidth = 3;
                    ctx.strokeRect(col, row, gridSize, gridSize);
                }
    
                function redraw() {
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0);
                    drawGrid();
                    drawCellNumbers();
                }
    
                canvas.addEventListener('mousemove', function(event) {
                    const rect = canvas.getBoundingClientRect();
                    const scaleX = canvas.width / rect.width;
                    const scaleY = canvas.height / rect.height;
                    const mouseX = (event.clientX - rect.left) * scaleX;
                    const mouseY = (event.clientY - rect.top) * scaleY;
    
                    const cellCoords = getCellCoords(mouseX, mouseY);
    
                    if (highlightedCell && (highlightedCell.col !== cellCoords.col || highlightedCell.row !== cellCoords.row)) {
                        redraw();
                    }
    
                    highlightedCell = cellCoords;
                    highlightCell(cellCoords.col, cellCoords.row);
                });
    
                canvas.addEventListener('click', function(event) {
                    const rect = canvas.getBoundingClientRect();
                    const scaleX = canvas.width / rect.width;
                    const scaleY = canvas.height / rect.height;
                    const mouseX = (event.clientX - rect.left) * scaleX;
                    const mouseY = (event.clientY - rect.top) * scaleY;
    
                    const cellCoords = getCellCoords(mouseX, mouseY);
    
                    const tooltipMapX = cellCoords.col / scaleX + canvas.offsetLeft;
                    const tooltipMapY = cellCoords.row / scaleY + canvas.offsetTop + gridSize;
    
                    tooltipMap.style.left = `${tooltipMapX}px`;
                    tooltipMap.style.top = `${tooltipMapY}px`;
                    tooltipMap.style.display = 'block';
    
                    buyButton.onclick = function() {
                        const cellNumber = Math.floor(mouseY / gridSize) * (1000 / gridSize) + Math.floor(mouseX / gridSize) + 1;
                        alert(`Has comprado la celda número ${cellNumber}`);
                        tooltipMap.style.display = 'none'; // Ocultar el tooltipMap tras la compra
                    };
                });
    
                canvas.addEventListener('mouseleave', function() {
                    tooltipMap.style.display = 'none';
                });
            };
    
            img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/000080_Navy_Blue_Square.svg/2048px-000080_Navy_Blue_Square.svg.png';
        });
    canvas {
        position: relative;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
    
    .tooltipMap {
        position: absolute;
        display: none;
        background-color: white;
        border: 1px solid black;
        padding: 5px;
        box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
        border-radius: 5px;
        font-size: 14px;
        z-index: 10;
    }
    
    .tooltipMap button {
        padding: 5px 10px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 3px;
        cursor: pointer;
    }
    
    .tooltipMap button:hover {
        background-color: #0056b3;
    }
    <div id="tooltipMap" class="tooltipMap">
        <p>Comprar esta celda</p>
        <button id="buyButton">Comprar</button>
    </div>
    
    <canvas id="gameMap" width="1000" height="1000"></canvas>

    If you are happy for the tooltip’s position to be calculated relative to the mouse pointer itself, rather than relative to the cell underneath the mouse pointer, you could simplify your click event handler by removing all the scaling code and just using the raw mouse coordinates.