V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
TomVista
V2EX  ›  问与答

html 图片滚轮放大缩小,出了点问题,谁帮忙看一下

  •  1
     
  •   TomVista · 2020-05-19 07:51:59 +08:00 · 768 次点击
    这是一个创建于 1431 天前的主题,其中的信息可能已经有所发展或是发生改变。

    效果是以鼠标为中心缩放图片,

    不知道为什么,我写的这个每次缩放都会偏一点.

    <body>
    
      <div class="content" >
        <div id="box" style="background-size: cover;" class="box" onmousewheel="zoom(event)" onclick="clic(event)"></div>
      </div>
    
    </body>
    <script>
      let scale = 1
      let width = 1000
      let height = 500
      let imagetop = 0
      let imageleft =0
      const box = document.querySelector('#box')
      function zoom(event) {
        let oldscale = scale
        if (event.deltaY > 0) {
          scale += 0.1
        } else {
          scale -= 0.1
        }
        
        box.style.width = `${width * scale}px`
        box.style.height = `${height * scale}px`
        box.pageX
    
        const offsetx = event.offsetX * (scale-oldscale)
        const offsety =event.offsetY *  (scale-oldscale)
    
        console.log(offsetx,offsety)
        box.style.top = `${imagetop -offsety}px`
        box.style.left = `${imageleft -offsetx}px`
        imagetop -=offsety
        imageleft-=offsetx
      }
    
      function clic(event){
        console.log(event.offsetX)
      }
    </script>
    <style>
      .content {
        height: 200px;
        width: 200px;
        overflow: hidden;
        position: relative;
      }
    
      .box {
        height: 500px;
        width: 1000px;
        background: url( https://s1.ax1x.com/2020/05/18/Yh0yi4.jpg);
        position: absolute;
      }
    </style>
    
    第 1 条附言  ·  2020-05-19 09:04:53 +08:00

    错误在这里,

    不够小学几何水平,:dog

    在一个矩形内,有一个点p(x,y),将矩形缩放s1倍,在缩放至s2倍,p1,p2分别是缩放之后的p点,分别求出p1,p2的横纵坐标差

        const offsetx = event.offsetX * (scale-oldscale)
        const offsety =event.offsetY *  (scale-oldscale)
    
    x *(s1-s2)
    y*(s1-s2)
    

    正确答案应该是

    x/width *s1*width - x/width *s2*width = x*s1-x*s2  // ???我特么又算错了
    
    
    
    
    // 鼠标所在的位置是p1而不是p,
    
    在一个矩形内,有一个点p,将矩形缩放s1倍,在缩放至s2倍,p1(x,y),p2分别是缩放之后的p点,分别求出p1,p2的横纵坐标差
    
    p2x/p1x = s2/s1
    
    p2x-p1x=(s2-s1)/s1*x // mdzz
    
    
    第 2 条附言  ·  2020-05-19 09:06:37 +08:00
    昨天下班折腾到 12 点,md
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1484 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:12 · PVG 01:12 · LAX 10:12 · JFK 13:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.