首页 > 解决方案 > 鼠标悬停时在棋盘上突出显示一个正方形

问题描述

我在画布上画了一个棋盘,我想突出显示鼠标所在的方块。我已经尝试过了,但我能得到的最远距离是半个平方不同步。

这是我的代码:

canvas.addEventListener('mousemove', function(evt)
{
    const position = getGridPoint(evt);

    drawBoard(); //Clears the last highlight

    context.lineWidth='3'; //Draws the new highlight
    context.strokeStyle = 'yellow';
    context.rect(position.x * board.squareW, position.y * board.squareH, board.squareW, board.squareH);
    context.stroke();
})

function getGridPoint(evt)
{
    const rect = canvas.getBoundingClientRect();

    //board.w = width of the board
    //board.squareW = width of each tile on the board

    const x = Math.round((evt.clientX - rect.left) / (rect.right - 2 - rect.left) * board.w);
    const y = Math.round((evt.clientY - rect.top) / (rect.bottom - 2 - rect.top) * board.h);

    const roundX = Math.round(x / board.squareW);
    const roundY = Math.round(y / board.squareH);

    return {
        x: roundX,
        y: roundY
    };
}

它在我使用 math.round 的第二个函数中

因此,如果我手动从 x 和 y 中减去半个图块的宽度,它会起作用,但这似乎是一种 hacky 方式,我宁愿首先正确地做到这一点

JSfiddle:http: //jsfiddle.net/5toudex0/3/

标签: javascript

解决方案


试试这个getTile

function getTile(evt)
{
    const rect = canvas.getBoundingClientRect();

    //board.w = width of the board
    //board.squareW = width of each tile on the board

    const x = Math.floor((evt.clientX - rect.left) / board.squareW);
    const y = Math.floor((evt.clientY - rect.top) / board.squareH);
    return {
        x: x,
        y: y
    };
}

推荐阅读