Can you get mouse position relative to canvas?Monkey Programming Forums/HTML5/Can you get mouse position relative to canvas?
| I finished my first app today and made a web page for it, intending to have some text above the app (and later, maybe, ads).|
Alas, I found it didn't work because the mouse position is relative to the top left of the web page itself. So for now I put the app back at the top left.
Of course there are workarounds for this, but it would be nice if you could get mouse position relative to the canvas, or just get the canvas coords on the page. Anyone know how to do this?
Obviously one could code HTML for a fixed size and put the resulting coordinates into the app by hand.
Alas, I found it didn't work because the mouse position is relative to the top left of the web page itself.
What browser are you using? IE9 and Chrome 16 report canvas-related coordinates, according to my tests. (I inserted a H1 element before the canvas element in the generated html file.)
This is my test code:
Save the following files into a project folder.
| I did some more experimentation. Looks like the problem is just with the scrollbar (which Mark has cleverly eliminated in his default style sheet). I must have scrolled without realising it. Stuff on the page above the app doesn't cause a problem (though with so many laptops around there won't be room for much anyway if we can't scroll).|
IE and Firefox both fail when you scroll down (the mouse pointer is displaced on the canvas). Chrome seems to cope perfectly. Those are the three browsers I tried.
If you want to experiment,
is the same as patternmatch.htm but with a table on top and a scrollbar.
Oh well, I can live without a scrollbar, I suppose (but is it really life?)
| It's the same for me.|
I have a monkey canvas after headers and texts.
On Chrome I can scroll the page and have right mouse coordinates all the time.
On IE9, the page should stay at the top for good coords. Which makes the bottom of the game unreachable with a small screen.
Unlike Gerry, I can't live without the scroll bar.
You may say it's not a bug, but then it's a very annoying inconsistency.
I'm surprised that we are just 2 to suffer from that ?
I'll try impixi solution, but I don't have an absolute canvas position...
| Just wondering, has anyone come up with a nice workaround / fix for this? |