我現在正在爲此苦苦掙扎。我在畫布上繪製一個網格。我添加一個mousemove eventHandler並跟蹤mouseX和mouseY的位置。我希望能夠計算從鼠標位置到網格中項目的距離。我似乎無法做到這一點,我嘗試了一些不同的解決方案,比如在mousemove處理程序中添加一個循環並使用requestAnimationFrame,但兩種解決方案都非常緩慢。鼠標靠近對象Javascript
這裏是我下面的代碼:
function setupCanvas(){
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
blockWidth = width/2 - 150;
blockHeight = height/2 - 100;
gridArray = [];
gridWidthArray = [];
ctx.fillRect(0,0,width,height);
//drawGrid();
drawInitGrid();
canvas.addEventListener('mousemove',onMouseMoveHandler);
}
function drawInitGrid(){
for(x = 0; x<16; x++){
for(y = 0; y<11; y++){
var gridBlock = new GridBlock((blockWidth) + x*20, (blockHeight) + y*20, blockWidth, blockHeight);
gridBlock.render(ctx);
gridArray.push(gridBlock);
//gridWidthArray.push(gridBlock.xPos)
}
}
}
function onMouseMoveHandler(e){
if(containerBounds(e)){
mouseX = e.offsetX;
mouseY = e.offsetY;
console.log(mouseX, mouseY);
//console.log(gridWidthArray);
for(var grid in gridArray){
//console.log(gridArray[grid].xPos)
}
}
}
我也試過在網格塊對象添加的MouseEvent,但也似乎不工作。
你能提供一個可行的例子嗎? (jsfiddle左右) – dwana 2015-02-06 10:12:54
我剛剛設置了這個 - http://codepen.io/fried/pen/YPENQg雖然由於某種原因 - 無法讓mousehandler在示例中正常工作 – Fred 2015-02-06 10:35:38