Bob Bob - 3 months ago 13
HTML Question

Detect click events on canvas elements on different monitor sizes

Hello Stack Overflow Buddies,

My question today is about click events on canvas (html). I'm making some cool games using canvas on my own laptop and I required click events on the elements I created. I came across that problem easily by using the awesome jQuery

$("canvas").click(function () {//Blah, Blah, Blah})
but had to add variables for the distance from the top of the page to the top of the canvas and the left side of the page to the left side of the canvas. However, I've realized the problem that if I changed computers with the same variables and the monitor size changed, the variables would have to change as well to compensate (this would not matter if the canvas was on the very top left of the page).

How would I be able to still be able to fire the click events accurately but on different monitor sizes? Is there another solution for this?

I would be happy to place down an example if you need it.

Edit: The canvas is centered so if the monitor size is changed, the pixels to the left or right would increase/decrease. The variables I set was from trial and error which is very unreliable (I know), so is there another way to do this?

Answer

You can use the native MouseEvent properties offsetX and offsetY to get the click position relative to the position of your canvas.

Here is a demo of that using a div but it works just the same on a canvas.

Comments