Javascript 鼠标悬停时高亮显示棋盘格上的正方形

Javascript 鼠标悬停时高亮显示棋盘格上的正方形,javascript,Javascript,我在画布上画了一个棋盘格,我想突出显示鼠标所在的正方形。我已经试过了,但我能做的最远的就是让它失去同步 这是我的密码: canvas.addEventListener('mousemove', function(evt) { const position = getGridPoint(evt); drawBoard(); //Clears the last highlight context.lineWidth='3'; //Draws the new highlig

我在画布上画了一个棋盘格,我想突出显示鼠标所在的正方形。我已经试过了,但我能做的最远的就是让它失去同步

这是我的密码:

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减去半个瓷砖的宽度,它会起作用,但这似乎是一种很有技巧的方法,我宁愿一开始就正确地做


jsidle:

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
    };
}

只需对画布的mousemove处理程序进行一点更改,就可以(0)直接获得鼠标的客户端位置,然后(1)计算要高亮显示的平铺的列/行索引

考虑对代码进行以下更改:

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

  var xPos = evt.clientX, yPos = evt.clientY;
  var xTileIndex = (xPos / board.squareW)>>0;
  var yTileIndex = (yPos / board.squareH)>>0;
  console.log(`x,y = ${xPos},${yPos}`);
  console.log(`x,y = ${xTileIndex},${yTileIndex}`);

你能发布足够的代码让我们重现你的问题吗?理想情况下,在你的问题中创建一个可以轻松复制到答案中的实时片段,作为提供答案的基础。(0)鼠标光标的客户端命令和(1)瓷砖的尺寸。将客户pos除以平铺大小,就得到了答案。我会想出一个答案的。谢谢你!另一个家伙发布了一个答案,第一个有效,但我也感谢你的回答:)谢谢