Home > Web Front-end > JS Tutorial > How Do I Get Mouse Click Coordinates on a Canvas Element in JavaScript?

How Do I Get Mouse Click Coordinates on a Canvas Element in JavaScript?

DDD
Release: 2024-12-06 06:17:10
Original
133 people have browsed it

How Do I Get Mouse Click Coordinates on a Canvas Element in JavaScript?

Retrieving Mouse Click Coordinates on a Canvas Element

This question revolves around obtaining the precise coordinates of a mouse click relative to a canvas element. For modern browsers like Safari, Opera, and Firefox, a streamlined solution exists that obviates the need for jQuery.

The provided JavaScript code offers an eloquent approach to this task:

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);
}

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

This code efficiently captures the mouse click position by leveraging the getBoundingClientRect() method and calculating the relative x and y coordinates. The console.log() call displays these coordinates, providing a clear indication of the click's location within the canvas element.

The above is the detailed content of How Do I Get Mouse Click Coordinates on a Canvas Element in JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template