HTML5/Canvas Mouse Position off when placed in actual Site
I'm capturing mouse position like this
mouse_move: function(e)
{
mousePos.x = e.pageX - vr.o.context.canvas.offsetLeft;
mousePos.y = e.pageY - vr.o.context.canvas.offsetTop;
},
and开发者_运维问答 it has worked like a dream in all modern browsers while in development, Even tested Wrapping the <canvas/>
in a basic dom structure to make sure mouse position adjusted...
obviously now I'm putting it in the actual site it's not working...
You can see here http://jondavidjohn.com/projects/
the mouse position ends up quite a ways south of the actual cursor, anything specifically that could be causing this?
SOLUTION
mouse_move: function(e)
{
mousePos.x = e.offsetX;
mousePos.y = e.offsetY;
},
COPIED FROM: http://simonsarris.com/blog/510-making-html5-canvas-useful
Getting mouse coordinates on Canvas
Getting good mouse coordinates is a little tricky on Canvas. You could use offsetX/Y and LayerX/Y, but LayerX/Y is deprecated in webkit (Chrome and Safari) and Firefox does not have offsetX/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.
Then you simply subtract that offset from the e.pageX/Y values and you’ll get perfect coordinates in almost every possible situation.
// 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};
}
Use e.offsetX and e.offsetY for now instead.
It actually gets more complicated when you introduce some other things, like margins and padding, but offsetX and offsetY will be much more accurate than what you've got to say the least.
I don't have my new "bulletproof-works-in-every-situation" mouse code on me right now, I can get that later for you if you think you'll need it.
edit: Derp! Thanks chopperdave for finally providing the code I forgot to add!
精彩评论