图片定点缩放(稳定版),以鼠标为中心点进行缩放

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        width: 360px;
        aspect-ratio: 16/9;
        overflow: hidden;
      }
      .wrap {
        /* position: relative; */
        width: 100%;
        height: 100%;
      }
      .img {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="wrap">
        <img class="img" src="./test.png" alt="" />
      </div>
    </div>
  </body>
  <script>
    const container = document.querySelector(".container");
    const wrap = document.querySelector(".wrap");
    const img = document.querySelector(".img");

    let factor = {
      x: 0,
      y: 0,
    };
    let scale = 1;

    container.addEventListener("wheel", (e) => {
      wrap.style.transformOrigin = "0 0";

      const { width, height } = wrap.getBoundingClientRect();
      const { offsetX, offsetY } = e;
      console.log(width, height);

      let _scale = scale;
      _scale += e.deltaY < 0 ? -0.1 : 0.1;
      if (_scale <= 1) {
        factor = {
          x: 0,
          y: 0,
        };
        scale = 1;
        wrap.style.transform = `translate(${factor.x}px, ${factor.y}px) scale(${scale})`;
        return;
      }
      const oWidth = width * scale;
      const oHeight = height * scale;

      const nWidth = width * _scale;
      const nHeight = height * _scale;

      const dWidth = oWidth - nWidth;
      const dHeight = oHeight - nHeight;

      const ratioX = offsetX / width;
      const ratioY = offsetY / height;

      const deltaX = dWidth * ratioX;
      const deltaY = dHeight * ratioY;

      factor.x += deltaX;
      factor.y += deltaY;

      scale = _scale;

      wrap.style.transform = `translate(${factor.x}px, ${factor.y}px) scale(${scale})`;
    });
  </script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值