复制自: http ://simonsarris.com/blog/510-making-html5-canvas-useful
在画布上获取鼠标坐标
在 Canvas 上获得良好的鼠标坐标有点棘手。您可以使用 offsetX/Y 和 LayerX/Y,但在 webkit(Chrome 和 Safari)中不推荐使用 LayerX/Y,并且 Firefox 没有 offsetX/Y。
获得正确鼠标位置的最防弹方法如下所示。您必须沿着树向上添加偏移量。然后,您必须向偏移添加任何填充或边框。最后,当页面上有固定位置的元素(如 wordpress 管理栏或 stumbleupon 栏)时,要解决坐标问题,您必须添加的 offsetTop 和 offsetLeft。
然后,您只需从 e.pageX/Y 值中减去该偏移量,您就会在几乎所有可能的情况下获得完美的坐标。
// Creates an object with x and y defined,
// set to the mouse position relative to the state's canvas
// If you wanna be super-correct this can be tricky,
// we have to worry about padding and borders
CanvasState.prototype.getMouse = function(e) {
var element = this.canvas, offsetX = 0, offsetY = 0, mx, my;
// Compute the total offset
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar
offsetX += this.stylePaddingLeft + this.styleBorderLeft + this.htmlLeft;
offsetY += this.stylePaddingTop + this.styleBorderTop + this.htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object (a hash) with x and y defined
return {x: mx, y: my};
}