V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
TomVista
V2EX  ›  问与答

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

  •  1
     
  •   TomVista · May 19, 2020 · 1057 views
    This topic created in 2181 days ago, the information mentioned may be changed or developed.

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

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

    <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>
    
    Supplement 1  ·  May 19, 2020

    错误在这里,

    不够小学几何水平,: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
    
    
    Supplement 2  ·  May 19, 2020
    昨天下班折腾到 12 点,md
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1061 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 18:36 · PVG 02:36 · LAX 11:36 · JFK 14:36
    ♥ Do have faith in what you're doing.