Home >Web Front-end >JS Tutorial >How Can I Get Precise Mouse Click Coordinates on a Canvas Element?

How Can I Get Precise Mouse Click Coordinates on a Canvas Element?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 06:54:07883browse

How Can I Get Precise Mouse Click Coordinates on a Canvas Element?

Determining Mouse Click Coordinates on Canvas Elements

Retrieving the precise coordinates of mouse clicks within a canvas element is a common need in various programming applications. The following guide provides a straightforward approach for web browsers including Safari, Opera, and Firefox.

Cross-Browser Solution

To achieve a simple and cross-browser solution, a JavaScript function named getCursorPosition can be defined:

function getCursorPosition(canvas, event) {
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    console.log("x: " + x + " y: " + y);
}

This function calculates the coordinates relative to the canvas element itself.

Event Handling

To attach this functionality to a canvas element, add an event listener for mouse down events:

const canvas = document.querySelector('canvas');
canvas.addEventListener('mousedown', function(e) {
    getCursorPosition(canvas, e);
});

Once a mouse click is detected, the getCursorPosition function is invoked, and the x and y coordinates of the click are logged to the console.

The above is the detailed content of How Can I Get Precise Mouse Click Coordinates on a Canvas Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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