我在DOM中有一个图像,我想以其自然的宽度和高度(而不是适合容器的宽度)获得相对于图像的鼠标单击坐标。例如,当鼠标单击图像时,它会返回坐标(50,50),它们是图像在其实际尺寸上的实际单击坐标。
任何想法如何做到这一点?
const getCoords = (e) => {
e = (e||window.event);
let absoluteCoords = {
x: e.pageX - e.target.getBoundingClientRect().left,
y: e.pageY - e.target.getBoundingClientRect().top
}
return {
x: absoluteCoords.x / e.target.clientWidth * e.target.naturalWidth,
y: absoluteCoords.y / e.target.clientHeight * e.target.naturalHeight
};
}
<img src="https://wow.olympus.eu/webfile/img/1632/oly_testwow_stage.jpg?x=1024" onclick="console.log( getCoords(event) )"/>
$("#img-container img").click((e) => {
// image reference
const img = $("#img-container img");
// consider scrolled page amount for later calcualtions
const scrollTop = $("body").scrollTop();
const scrollLeft = $("body").scrollLeft();
// calculate click x, y coords
let x = e.pageX + scrollLeft - e.target.offsetLeft;
let y = e.pageY + scrollTop - e.target.offsetTop;
// get original image dimensions
const originalWidth = e.target.naturalWidth;
const originalHeight = e.target.naturalHeight;
// calcualte the difference in dimensions with current image
const deltaWidth = originalWidth / img.width();
const deltaHeight = originalHeight / img.height();
// multiply the difference with x,y coords
x = Math.round(x * deltaWidth);
y = Math.round(y * deltaHeight);
console.log(x, y);
});
感谢大家的帮助