点击图像,获取坐标。

11
我有一个标准的HTML图像标签,其中包含一个尺寸为100x100像素的图像。 我希望人们能够点击图像,并将他们点击的X和Y传递到函数中。
这些坐标需要相对于图像的顶部和左侧进行计算。

1
这个线程完全回答了同样的<a href="http://bytes.com/forum/thread507079.html">问题</a>,更多信息请参见<a href="http://www.quirksmode.org/js/events_properties.html#position">此处</a>。 - Pat
3个回答

5

1
根据您的描述,您应该注册图像鼠标事件,对于这种情况,您应该有图像鼠标按钮事件。
在函数中,您应该使用:
Point mousePoint = e.GetPosition( this );

这将根据左上角点的像素值给出鼠标位置。

然后在mousePoint处,您可以打印X和Y信息。


1
用你的图片替换画布,它将起到相同的作用。

let img = document.getElementById("canvas");

img.x = img.getBoundingClientRect().left;
img.y = img.getBoundingClientRect().top;

function click(e) {
  document.getElementById("output").innerHTML = "X coords: " + (e.clientX - img.x) + "<br> Y coords: " + (e.clientY - img.y);
}

img.addEventListener("click", click);
<!--- Like a image --->
<canvas id="canvas" width="100" height="100"></canvas>
<p id="output"></p>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接