我有一个图像16000x9000,该图像显示在一个简单的页面上,其容器的大小已预定义。
myimage.onclick = function(e) {
console.log(e.x, e.y);
};
<p>Image to use:</p>
<img id="myimage" width="900px" height="500px" src="https://via.placeholder.com/150C/O https://placeholder.com/">
我想按图像单击并获得像素坐标。当我按图像单击时,收到{x {1}}的输出为900x500,这显然是不正确的数据,并且还有其他含义。
当我单击右下角时,我希望得到的值近似于原始图像的宽度/高度。
如何获取此数据?
答案 0 :(得分:1)
您可以做一些数学运算来比较元素的大小和原始图像的大小。
myimage.onclick = function(e) {
var ratioX = e.target.naturalWidth / e.target.offsetWidth;
var ratioY = e.target.naturalHeight / e.target.offsetHeight;
var domX = e.x + window.pageXOffset - e.target.offsetLeft;
var domY = e.y + window.pageYOffset - e.target.offsetTop;
var imgX = Math.round(domX * ratioX);
var imgY = Math.round(domY * ratioY);
console.log(imgX, imgY);
};
<p>Image to use:</p>
<img id="myimage" width="900px" height="500px" src="https://via.placeholder.com/80x40">