Open In App

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

Last Updated : 22 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Create a JavaScript function getMousePosition that takes the canvas element and the event object as parameters.
  • Use getBoundingClientRect() to get the position and size information of the canvas relative to the viewport.
  • Calculate the mouse coordinates (x and y) by subtracting the canvas’s left and top positions from the event’s client coordinates.

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.

html




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

cordiates

Output



Like Article
Suggest improvement
Share your thoughts in the comments