2017-05-06 78 views
1

我有一個畫布,上面有許多柵格,並且會顯示一個文本。我也需要用戶與畫布交互。畫布上的鼠標移動高亮顯示正方形

我想突出顯示相應的方塊,當用戶在畫布上拖動鼠標或點擊它時。

我無法選擇使用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

您所連結的的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(); 
    } 

}); 

希望我能幫忙! :-)

+0

謝謝你的幫助,但是當我粘貼這個小提琴時,它沒有突出顯示我點擊的網格,我不希望它在黑色部分突出顯示,它應該突出顯示在灰色部分(即。廣場)。我怎樣才能得到我想突出的廣場? – RemyaJ

+0

您可以檢查行和列是否> 0,以及行和列是否都是奇數。如果所有這些條件都通過了,那麼你畫黃色的方塊。 –

+0

如果我能夠幫助,請upvote我的答案!因爲我是新用戶,所以我想贏得聲譽。 –