首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >画布高亮方块鼠标移动

画布高亮方块鼠标移动
EN

Stack Overflow用户
提问于 2017-05-06 15:18:51
回答 1查看 1K关注 0票数 1

我有一个帆布,上面有许多网格,文字会显示在上面。我也需要与画布进行用户交互。

当用户将鼠标拖到画布上或点击它时,我想突出显示相应的方块。

我无法选择使用Javascript突出显示的网格。发布整个代码- 琴键

我试过了,但没有用。

代码语言: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();
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-07 05:26:20

你所链接的小提琴有几个问题:

首先,x和y值是NaN,因为$('.canvasld').offsetLeft)是未定义的。在JQuery中,查询中没有offsetLeft属性。

您可以使用JQuery .offset()方法,该方法返回具有leftright属性的对象。

其次,您的contextcanvasConfig都是未定义的。

下面是有问题的代码片段,并纠正了这些问题。我使用默认对象来代替不存在的canvasConfig:

代码语言:javascript
复制
// 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();
  }

});

希望我能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43822098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档