将img中的onclick区域限制为可缩放

piztneat  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(158)

我有一个美式足球场的png,我想显示用户点击球场时的码数,以进行缩放。图像还包括实际场线之外的场区域。
这里是代码沙箱
我可以根据Map找到院子 onClick 函数,但我想将可单击区域限制为仅在字段本身内,因为当前它返回图像中单击任意位置的x和y坐标。有没有办法用javascript实现这一点?该解决方案还需要根据分辨率和设备进行扩展。

function App() {
  const [x, setX] = useState(0);
  const [yards, setYards] = useState(0);
  const printCoordinates = (e) => {
    const { width, height } = e.target.getBoundingClientRect();
    const { offsetX, offsetY } = e.nativeEvent;

    setX(Math.round((((offsetX / width) * 100 - 10) / 80) * 100));
  };

  const hoverAction = (e) => {
    const { width } = e.target.getBoundingClientRect();
    const { offsetX } = e.nativeEvent;
    setYards(Math.round((((offsetX / width) * 100 - 10) / 80) * 100));
  };

  return (
    <Row>
      <Col sm={4}>{x <= 0 ? 0 : x >= 100 ? 100 : x} yards</Col>
      <Col sm={8}>
        <Container>
          <img
            id="football-field"
            src={footballField}
            alt="football-field"
            style={{ width: "80%", height: "80%" }}
            onClick={(e) => printCoordinates(e)}
            onMouseMove={(e) => {
              hoverAction(e);
            }}
            title={yards}
          />
        </Container>
      </Col>
    </Row>
  );
}

export default App;

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题