2

I need to get the x and y coordinates of where I clicked on an HTML5 canvas element. I did the following for the y coordinate:

 $("#my_canvas").click(function(event) {
        alert(Math.floor(event.clientY-$(this).offset().top));
 });

This gives me what appears to be the correct y coordinate. The problem is if you scroll down, clientY gets smaller because it seems to be measuring the y coordinate on the screen, disregarding the scrolling. So the above gives a negative number.

What is the proper way to get the x and y coordinate?

user1779563
  • 770
  • 3
  • 7
  • 13

1 Answers1

1

Use pageY instead of clientY, so that both the coordinates you compare are relative to the document :

event.pageY-$(this).offset().top
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758