Open In App

How to get the coordinates of a mouse click on a canvas element ?

The coordinates of the mouse whenever a click takes place can be found by detecting the click event with an event listener and finding the event’s x and y positions. In this article we are going to learn How to get the coordinates of a mouse click on a canvas element.

Approach

The getBoundingClientRect() method provides the position and size information of an element relative to the viewport. Used for accurate positioning, it returns an object with properties like left, top, right, bottom, width, and height. In the context of a canvas, it enables precise calculation of mouse coordinates for interaction.



Example: This example shows the fetching of coordinates of a mouse click on a canvas element.




<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to get the coordinates of a mouse
        click on a canvas element?
    </title>
</head>
 
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
 
    <b>
        How do I get the coordinates of a
        mouse click on a canvas element?
    </b>
 
    <p>
        Click anywhere on the canvas element
        to get the mouse pointer location.
    </p>
 
    <p>
        The size of the canvas
        is a square of 200px.
    </p>
 
    <p>Check the console for the output.</p>
 
    <canvas width="200" height="200"
            style="background-color: green">
    </canvas>
 
    <script type="text/javascript">
        function getMousePosition(canvas, event) {
            let rect = canvas.getBoundingClientRect();
            let x = event.clientX - rect.left;
            let y = event.clientY - rect.top;
            console.log("Coordinate x: " + x,
                "Coordinate y: " + y);
        }
 
        let canvasElem = document.querySelector("canvas");
 
        canvasElem.addEventListener("mousedown", function (e) {
            getMousePosition(canvasElem, e);
        });
    </script>
</body>
 
</html>

Output:



Output


Article Tags :