我现在正在为此苦苦挣扎。我在画布上绘制一个网格。我添加一个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