canvas onclick坐标使用getBoundingClientRect总是相同的 [英] canvas onclick coordinates using getBoundingClientRect always the same
本文介绍了canvas onclick坐标使用getBoundingClientRect总是相同的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用getBoundingClientRect获取我点击画布的坐标,但总是得到相同的结果。
我的代码在这里: http://fiddle.jshell.net/nH74F/1/
你可以看到我总是得到8,8
不知道为什么,有另一种方式获得这个信息吗?
解决方案
这是因为你总是使用 getBoundingClientRect
返回的元素的绝对位置,
<$ c $ c> canvas.addEventListener('click',function(e){//使用事件参数
var rect = canvas.getBoundingClientRect(); //获取元素的abs。position
var x = e.clientX - rect.left; //获取鼠标x并调整el。
var y = e.clientY - rect.top; //获取鼠标y并调整el。
alert('Mouse position:'+ x +','+ y);
...
I am trying to use getBoundingClientRect to get the coordinates of my click on canvas, but am always getting the same result.
My code is here: http://fiddle.jshell.net/nH74F/1/
As you can see i always get 8,8
No idea why, is there another way to get this info?
解决方案
That's because you always use the absolute position of the element returned by getBoundingClientRect
, and not the mouse position.
Try this instead:
canvas.addEventListener('click', function(e) { // use event argument
var rect = canvas.getBoundingClientRect(); // get element's abs. position
var x = e.clientX - rect.left; // get mouse x and adjust for el.
var y = e.clientY - rect.top; // get mouse y and adjust for el.
alert('Mouse position: ' + x + ',' + y);
...
这篇关于canvas onclick坐标使用getBoundingClientRect总是相同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文