echofool Posted March 6, 2012 Share Posted March 6, 2012 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 More sharing options...
justsomeguy Posted March 7, 2012 Share Posted March 7, 2012 Get the position of the canvas itself on the page and use that as an offset to figure out where the mouse is inside the canvas. Link to comment Share on other sites More sharing options...
echofool Posted March 7, 2012 Author Share Posted March 7, 2012 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 More sharing options...
justsomeguy Posted March 7, 2012 Share Posted March 7, 2012 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.