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

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

Patricia Arquette
Release: 2024-12-08 14:34:15
Original
606 people have browsed it

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

Getting Coordinates of Mouse Clicks on a Canvas Element

Determining the coordinates of mouse clicks on a canvas element is crucial for various applications. Here's a cross-browser solution that works in Safari, Opera, and Firefox:

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 snippet uses the getBoundingClientRect() method to obtain the canvas element's position within the document. It then calculates the x and y coordinates of the mouse click relative to the canvas element's origin.

By adding an event listener for the mousedown event, you can capture mouse clicks and retrieve the coordinates using the getCursorPosition function. This information can be further processed for various purposes, such as object manipulation or user interaction within the canvas element.

The above is the detailed content of How Can I Get Mouse Click Coordinates on 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