javascript - 鼠标悬停时在棋盘上突出显示一个正方形
问题描述
我在画布上画了一个棋盘,我想突出显示鼠标所在的方块。我已经尝试过了,但我能得到的最远距离是半个平方不同步。
这是我的代码:
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/
解决方案
试试这个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
};
}
推荐阅读
- flutter - Flutter - 无法编辑 pubspec.yaml 文件
- c - C中的赋值
- windows - 如何在 Windows 中循环处理 FFMpeg?
- python - 如何将 PyObject 转换为 C++ 数组?
- python-3.x - 不同的 Python 安装
- sql - LOAD DATA INPATH 表文件以 Impala 中的某个字符串开头
- processing - 如何修复这个太阳系模型的处理?
- angular - Angular 5: Is there way hide API call? or make it private?
- c# - 如何在 CsvHelper 中为所有类映射设置默认 NULL 值
- python-3.x - 使用递归打印从起点到目的地的所有路径 - Python