コピー元: http://simonsarris.com/blog/510-making-html5-canvas-useful
Canvasでのマウス座標の取得
Canvasでは、適切なマウス座標を取得するのは少し注意が必要です。offsetX/YとLayerX/Yを使用できますが、LayerX / YはWebkit(ChromeとSafari)で非推奨になり、FirefoxにはoffsetX/Yがありません。
正しいマウス位置を取得するための最も防弾の方法を以下に示します。オフセットを一緒に追加して、ツリーを上に移動する必要があります。次に、オフセットにパディングまたは境界線を追加する必要があります。最後に、ページ上に固定位置の要素(ワードプレスの管理バーやつまずきバーなど)がある場合の座標の問題を修正するには、'soffsetTopと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};
}