我有一个帆布,上面有许多网格,文字会显示在上面。我也需要与画布进行用户交互。
当用户将鼠标拖到画布上或点击它时,我想突出显示相应的方块。
我无法选择使用Javascript突出显示的网格。发布整个代码- 琴键
我试过了,但没有用。
$('.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();
});发布于 2017-05-07 05:26:20
你所链接的小提琴有几个问题:
首先,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();
}
});希望我能帮上忙!
https://stackoverflow.com/questions/43822098
复制相似问题