Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find mouse position relative to element

Tags:

javascript

I want to make a little painting app using canvas. So I need to find the mouse's position on the canvas.

like image 893
Ben Shelock Avatar asked Jul 13 '10 04:07

Ben Shelock


People also ask

How do you find the element position relative to a viewport?

Getting the relative position of an element The method element. getBoundingClientRect() provides the element's position and its relative position to the viewport. It returns an object that includes element's height, width, and its distance from the top, left, bottom, and right of the viewport.

How do I get my mouse position in react?

To get the mouse position in React: Set the onMouseMove prop on an element or add an event listener on the window object. Provide an event handler function. Access relevant properties on the event object.


1 Answers

As I didn't find a jQuery-free answer that I could copy/paste, here's the solution I used:

document.getElementById('clickme').onclick = function clickEvent(e) {       // e = Mouse click event.       var rect = e.target.getBoundingClientRect();       var x = e.clientX - rect.left; //x position within the element.       var y = e.clientY - rect.top;  //y position within the element.       console.log("Left? : " + x + " ; Top? : " + y + ".");     }
#clickme {   margin-top: 20px;   margin-left: 100px;   border: 1px solid black;   cursor: pointer; }
<div id="clickme">Click Me -<br> (this box has margin-left: 100px; margin-top: 20px;)</div>

JSFiddle of full example

like image 171
anytimecoder Avatar answered Oct 26 '22 20:10

anytimecoder