0

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?

Bob
  • 45
  • 1
  • 7
  • Is the clickable element centered? An example of your use case could clear questions up. – Frederik.L Sep 03 '16 at 18:57
  • The canvas is centered which is why if the monitor size is changed the pixels would change too. – Bob Sep 03 '16 at 18:59
  • Are you not getting these values dynamically? ie either through jQuery's `offset()` method or muniplation of `getBoundingClientRect()`? – Patrick Evans Sep 03 '16 at 19:01
  • This question seems similar to what you are looking for: http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas then you know what are relative positions when you create the elements. – Frederik.L Sep 03 '16 at 19:02
  • I physically had to go through trial and error to do this, any other way to do this? – Bob Sep 03 '16 at 19:03
  • Just don't forget to set `position:relative` to your canvas, as pointed out in comments. Programming is all the way trial and error, but you can cheat a little by looking at common mistakes :) – Frederik.L Sep 03 '16 at 19:07

1 Answers1

0

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.

geekonaut
  • 5,714
  • 2
  • 28
  • 30