Jump to content

Mouse position relative to canvas?


echofool

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...