Getting Mouse Coordinates Relative to Canvas Element
In an effort to create a simple canvas-based painting application, one common challenge is determining the mouse's position on the canvas.
Solution
One approach to solve this is by utilizing the BoundingClientRect property. This can be implemented as follows:
<code class="javascript">document.getElementById('clickme').onclick = function(e) { var rect = e.target.getBoundingClientRect(); var x = e.clientX - rect.left; var y = e.clientY - rect.top; console.log("Left: " + x + " ; Top: " + y + "."); };</code>
Example
<code class="html"><div id="clickme"> Click Me -<br> (this box has margin-left: 100px; margin-top: 20px;) </div></code>
Explanation
The above is the detailed content of How to Get Mouse Coordinates Relative to a Canvas Element?. For more information, please follow other related articles on the PHP Chinese website!