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.

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật