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 position.
A function is created which takes in the canvas element and event as parameters. The dimension of the canvas is found using the getBoundingClientRect() function. This method returns the size of an element and its position relative to the viewport.
The position of x-coordinate of the mouse click is found by subtracting the event’s x position with the bounding rectangle’s x position. The x position of the event is found using the ‘clientX’ property. The x position of the canvas element, i.e. the left side of the rectangle can be found using the ‘left’ property.
Similarly, the position of y-coordinate of the click is found by subtracting the event’s y position with the bounding rectangle’s y position. The y-position of the event is found using the ‘clientY’ property. The y-position of the canvas element, i.e. the top side of the rectangle can be found using the ‘top’ property.
This subtraction will compensate for the location of the canvas on the page as the event’s x and y position would be relative to the page and not the canvas.
To detect the click, the canvas element is first selected using the querySelector() method. The addEventListener() method is used on this element to listen the ‘mousedown’ event. This event is triggered whenever a mouse button is pressed down. The callback of this function is used to call the function created above to detect the position of the click.
- Before Clicking anywhere to canvas:
- After clicking in the canvas:
- How to get relative click coordinates on the target element using JQuery?
- How to distinguish left and right mouse click using jQuery?
- How to draw with mouse in HTML 5 canvas ?
- How to perform click-and-hold operation inside an element using jQuery ?
- How to click anywhere on the page except one element using jQuery ?
- How to change an element color based on value of the color picker value on click?
- How to get Pixel from HTML Canvas ?
- HTML | DOM Geolocation coordinates Property
- How to position a div at specific coordinates ?
- Minimum Manhattan distance covered by visiting every coordinates from a source to a final vertex
- Web HTMLCanvasElement API | Canvas Element width property
- jQuery | click() with Examples
- HTML | DOM click() Method
- How to remove focus around buttons on click?
- AngularJS | ng-click Directive
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.