I want to make a little painting app using canvas. So I need to find the mouse's position on the canvas.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With