Categories
JavaScript Answers

How to Get the Coordinates of a Mouse Click on a Canvas Element?

Spread the love

Sometimes, we may want to get the coordinates of a mouse on an HTML canvas element.

In this article, we’ll look at how to get the coordinates of a mouse click on a canvas element.

Add a mousedown Event Handler

We can get the coordinates of a mouse click from the event object we get from the mousedown event handler.

For instance, we can write the following HTML:

<canvas style="width: 200px; height: 100px">
</canvas>

Then we can write the following JavaScript code:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

const getCursorPosition = (canvas, event) => {
  const rect = canvas.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  console.log(x, y)
}

canvas.addEventListener('mousedown', (e) => {
  getCursorPosition(canvas, e)
})

We add a canvas element with width 200px and height 100px.

Then we get the canvas element with the document.querySelector method.

Then we get the canvas context with the getContext method.

And then we call moveTo to move the cursor to the given x, y coordinates.

And we call lineTo to draw a line to the given x, y coordinates.

Then we call stroke to draw the line.

Next, we create the getCursorPosition function to get the canvas and event parameters.

We call canvas.getBoundingClientRect to get the rect object, which has the left and top properties to get the x and y coordinates of the top-left corner.

Then we subtract that from the event.clientX and event.clientY properties that have the mouse coordinates of the screen that we clicked on.

Therefore, x and y has the mouse coordinates we clicked on on the canvas.

Finally, we call canvas.addEventListener to add the mousedown event listener.

In it, we call getCursorPosition to get the mouse coordinates we clicked on on the canvas and log it.

x and y are in pixels.

Also, we can get the offsetX and offsetY properties from the event object to get the coordinates of the canvas we clicked on.

For instance, we can write:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

const getCursorPosition = (canvas, event) => {
  const x = event.offsetX
  const y = event.offsetY
  console.log(x, y)
}

canvas.addEventListener('mousedown', (e) => {
  getCursorPosition(canvas, e)
})

to get the mouse coordinates without doing the calculations.

Conclusion

We can get the mouse coordinates of the location we clicked on on the canvas with a few properties from the mousedown event object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *