画布在鼠标移动时突出显示正方形

时间:2017-05-06 15:18:51

标签: javascript jquery canvas grid html5-canvas

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

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

我无法使用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();
});

1 个答案:

答案 0 :(得分:1)

你链接的jsfiddle有几个问题:

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

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

其次,您的contextcanvasConfig都未定义。

这里是相关代码的片段,其中纠正了这些问题。我使用你的默认对象代替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();
  }

});

希望我能帮忙! : - )

相关问题