Home > Web Front-end > JS Tutorial > How to Get Mouse Coordinates Relative to a Canvas Element?

How to Get Mouse Coordinates Relative to a Canvas Element?

Patricia Arquette
Release: 2024-11-03 03:58:02
Original
606 people have browsed it

How to Get Mouse Coordinates Relative to a Canvas Element?

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>
Copy after login

Example

<code class="html"><div id="clickme">
  Click Me -<br>
  (this box has margin-left: 100px; margin-top: 20px;)
</div></code>
Copy after login

Explanation

  1. When the mouse clicks on the element clickme, the onclick event handler is triggered.
  2. The getBoundingClientRect() method retrieves the element's position and size relative to the viewport.
  3. The e.clientX and e.clientY properties represent the mouse's absolute position within the viewport.
  4. By subtracting rect.left and rect.top from these absolute coordinates, we obtain the mouse's position relative to the element's top-left corner.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template