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