Jump to content

Mouse position relative to canvas?


echofool
 Share

Recommended Posts

Hey I am stuck trying to get the mouse position in a canvas relative to the canvas and not the entire page. The position of the canvas in my page effects what e.pageX and e.pageY are which is a problem. Is there a way to do this so canvas position in a page is not affecting it?I used this thinking it would be relative to canvas only but it is not the case:

canvas = document.getElementById("canvas");  ctx = canvas.getContext("2d"); canvas.addEventListener("mousedown", mousePos, false);

Any ideas ? Is it even possible?

Link to comment
Share on other sites

How though ?its using % based on user's screen... i tried this:

 function mousePos(e){var curleft = curtop = 0;	if (e.offsetParent) {		do {		   curleft += e.offsetLeft;		   curtop += e.offsetTop;		} while (e = e.offsetParent);	}}  canvas = document.getElementById("canvas");  ctx = canvas.getContext("2d");canvas.addEventListener("mousedown", mousePos, false);

But it doesn't work =/ curleft and curtop remain as 0

Edited by echofool
Link to comment
Share on other sites

If you want to get the position of the mouse in the canvas, then you need to get the position of the mouse on the page and the position of the canvas on the page. Subtract the canvas position from the mouse position and you have the position of the mouse in the canvas.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...