如何获取在HTML5画布上点击的坐标? [英] How to get the coordinates clicked on an HTML5 canvas?
问题描述
我需要获取我点击HTML5 canvas元素的位置的x和y坐标。我为y坐标做了以下:
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));
});
这让我看起来是正确的y坐标。问题是如果你向下滚动, clientY
变小,因为它似乎是在屏幕上测量y坐标,忽略滚动。所以上面给出一个负数。
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.
获得x和y坐标的正确方法是什么?
What is the proper way to get the x and y coordinate?
推荐答案
使用 pageY 代替 clientY
,以便您比较的两个坐标都是相对于文档:
Use pageY instead of clientY
, so that both the coordinates you compare are relative to the document :
event.pageY-$(this).offset().top
这篇关于如何获取在HTML5画布上点击的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!