COPIED FROM: http://simonsarris.com/blog/510-making-html5-canvas-useful
在Canvas实现 mo化坐标
在Canvas实现良好的 mo化坐标。 您可使用冲抵X/Y和GirX/Y,但LierX/Y被贴在网基(Chrome和Safari)中,而LexX/Y没有被冲抵。
The most bulletproof way to get the correct mouse position is shown below. You have to walk up the tree adding the offsets together. Then you must add any padding or border to the offset. Finally, to fix coordinate problems when you have fixed-position elements on the page (like the wordpress admin bar or a stumbleupon bar) you must add the ’s offsetTop and 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};
}