

The GetCoordinates function uses the window.event method to find the coordinates of the mouse when it is clicked. The following code is in the page header. Tip: To get the vertical coordinate (according to the client area) of the mouse pointer, use the clientY property. HTML5 Get mouse coordinatesĭefinition and Usage The clientX property returns the horizontal coordinate (according to the client area) of the mouse pointer when a mouse event was triggered. The clientX property returns the horizontal coordinate (according to the client area) of the mouse pointer when a mouse event was triggered. The dimension of the canvas is found using the getBoundingClientRect () function. A function is created which takes in the canvas element and event as parameters. 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. You can interact with the keyboard, but it's more interesting using the mouse events. Get the coordinates of a mouse click on Canvas in Javascript When you are working with the canvas element in Javascript sometimes you need to interact with the user.

This returns a rectangle object that gives you the current offset of the canvas relative to the page. An easy solution is to use the getBoundingClientRect method of the canvas object. If the user has scrolled the page that your canvas game is on, or used the browser zoom feature, it can mess up the accurate calculation of the mouse position.

Subtract the X and Y offsets of the canvas DOM element from the mouse position to get the local position inside the canvas.
