我在画布上画了一个棋盘,我想突出显示鼠标悬停的正方形。我已经试过了,但是我能得到的最远的是它不同步半个平方。
这是我的代码:
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中减去一半瓦片的宽度,它将起作用,但这似乎是一种怪诞的方式,并且id会在一开始就正确地完成
JSfiddle:http://jsfiddle.net/5toudex0/3/
答案 0 :(得分:0)
尝试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
};
}
答案 1 :(得分:0)
对画布的mousemove处理程序进行一些更改后,您可以(0)直接获取鼠标的客户端位置,然后(1)计算要突出显示的图块的col / row索引。
请考虑对代码进行以下更改:
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}`);