Home >Web Front-end >JS Tutorial >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}`); });
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!