我有一个 Canvas ,上面有很多网格,上面会显示文本。我还需要与 Canvas 进行用户交互。
当用户将鼠标拖动到 Canvas 上或单击 Canvas 时,我想突出显示相应的方 block 。
我无法选择我应该使用 Javascript 突出显示的网格。 发布整个代码 - fiddle-link
我尝试过这个,但它不起作用。
$('.canvasld').mousedown(function(e){
let x = e.clientX - $('.canvasld').offsetLeft,
y = e.clientY - $('.canvasld').offsetTop,
col = Math.floor(x /6),
row = Math.floor(y /6);
context.rect(x, y, 5, 5);
//pixel['enabled'] = true;
context.fillStyle = canvasConfig.options.enabledPixelColor;
context.fill();
});
最佳答案
您链接的 jsfiddle 有几个问题:
首先,您的 x 和 y 值为 NaN
,因为
$('.canvasld').offsetLeft)
未定义。在 JQuery 中,查询上没有 offsetLeft
属性。
您可以使用 JQuery .offset()
方法,该方法返回具有属性 left
和 right
的对象。
其次,您的 context
和 canvasConfig
均未定义。
以下是已纠正这些问题的相关代码片段。我使用您的默认对象来代替不存在的 canvasConfig:
// revised mousedown code
$('.canvasld').mousedown(function(e) {
// small square size
let squareSize = (defaults.pixelSize / 2);
// get the x and y of the mouse
let x = e.clientX - $('.canvasld').offset().left;
let y = e.clientY - $('.canvasld').offset().top;
// get the grid coordinates
let col = Math.floor(x / squareSize);
let row = Math.floor(y / squareSize);
// get the canvas context
let context = $('.canvasld')[0].getContext('2d');
// check if the square falls into the smaller grid
if(col > 0 && row > 0 && col % 2 > 0 && row % 2 > 0) {
// draw the rectangle, converting the grid coordinates back
// into pixel coordinates
context.rect(col * squareSize, row * squareSize, squareSize, squareSize);
context.fillStyle = defaults.enabledPixelColor;
context.fill();
}
});
希望能帮到你! :-)
关于javascript - 鼠标移动时 Canvas 突出显示方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43822098/