javascript.如何在图像上获得精确的触摸位置[复制]

tquggr8v  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(91)
    • 此问题在此处已有答案**:

How can I translate between client coordinates of a HTML video element and picture coordinates?(1个答案)
17小时前关门了。
我有一个图像。为此,我想让触摸事件开始,移动和结束。我需要触摸的确切图像像素。
问题是实际图像小于HTMLImageElement。(css样式object-fit: scale-down

我不需要HTMLimageElement的触摸事件,但需要实际的图像本身。
我该如何存档?
顺便说一句,我使用react(如果这有帮助的话),但我可以(希望)自己修改答案。
当前尝试:

<img ...
onTouchStart={(event) => {
  const touch = event.changedTouches[0];
  const rect = event.currentTarget.getBoundingClientRect();
  const pxlX = touch.screenX - rect.left;
  const pxlY = touch.screenY - rect.top;
  // other stuff with (pxlX, pxlY)
}} />

我的最终解决方案

import { useState } from "react";
import ImageSrc from "./assets/image.png";

export default function App() {
    const [text, setText] = useState("undefined");

    return <div className="w-screen h-screen overflow-hidden">
        <img src={ImageSrc} alt="" className="object-scale-down w-full h-full" onMouseMove={(event) => {
            const {x, y} = getXY(event);
            setText(`${x}/${y}`);
        }} />
        <span className="fixed top-0 left-0 pointer-events-none">{text}</span>
    </div>;
}

function getXY(event: React.MouseEvent<HTMLImageElement, MouseEvent>): {x: number, y: number} {
    const img = event.currentTarget;
    const [imgWidth, imgHeight] = [img.naturalWidth, img.naturalHeight];
    const [boxWidth, boxHeight] = [img.width, img.height];
    const imgRatio = imgWidth / imgHeight;
    const boxRatio = boxWidth / boxHeight;
    if (imgRatio < boxRatio) {
        const x0 = (boxWidth - boxHeight * imgWidth/imgHeight) / 2;
        const x = Math.round(event.nativeEvent.offsetX - x0);
        return {x: x, y: event.nativeEvent.offsetY};
    } else {
        const y0 = (boxHeight - boxWidth * imgHeight/imgWidth) / 2;
        const y = Math.round(event.nativeEvent.offsetY - y0);
        return {x: event.nativeEvent.offsetX, y: y};
    }
}
h7appiyu

h7appiyu1#

使用img. naturalHeight和img. naturalWidth确定有效图像开始的位置。
简单地说,如果事件的Y相对于图像上方的点,则以下量将为负,因此在事件中捕捉它并检查:

y0 = (400 - 400*mainImg.naturalHeight/mainImg.naturalWidth)/2;
var effectiveY = event.offsetY - y0;

这里涉及到一些数学问题,请随时询问当图像可以是肖像时,您是否需要一般描述,或者您是否仍然需要帮助来检测图像下方的事件。
x一个一个一个一个x一个一个二个一个x一个一个三个一个

相关问题