Home > Web Front-end > JS Tutorial > How Do I Get Mouse Click Coordinates on an HTML5 Canvas?

How Do I Get Mouse Click Coordinates on an HTML5 Canvas?

Barbara Streisand
Release: 2024-12-06 18:33:14
Original
568 people have browsed it

How Do I Get Mouse Click Coordinates on an HTML5 Canvas?

Getting Mouse Click Coordinates on a Canvas Element

To capture the coordinates of a mouse click on a canvas element, follow these steps:

Obtain the Canvas Element

Locate and access the canvas element using DOM selectors.

Add an Event Listener

Attach an event listener to the canvas to listen for mouse clicks.

Handle the Event

Within the event handler, use the getBoundingClientRect() method to retrieve the position of the canvas element on the screen.

Calculate the Coordinates

Subtract the client coordinates of the click from the canvas position to obtain the relative coordinates within the canvas.

Example Code:

const canvas = document.querySelector('canvas');

canvas.addEventListener('mousedown', function(event) {
  const rect = canvas.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  console.log(`Coordinates: X: ${x}, Y: ${y}`);
});
Copy after login

This solution is both simple and cross-browser compatible, ensuring that it works effectively in Safari, Opera, and Firefox.

The above is the detailed content of How Do I Get Mouse Click Coordinates on an HTML5 Canvas?. 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