Thursday, 19 January 2023

How to Incrementally Update an Elements Scale by Pinching with Js

The below code ALMOST works and I think I'm close yet quite far away from getting it to work properly. The problem is, the way the handlePinch function is set up. What actually happens when the user pinches to zoom a bit, is the square starts to accelerate. The more the user pinches, the faster the square zooms.

How can this be implemented that each time the user pinches to zoom, it incrementally scales, i.e. picking up where it left off without exceeding the max scale?

I'm stuck on this for two days and there doesn't seem to be any formula to show how something like this works. Note, I know there are libraries for this, I want to know how this works with vanilla js

const box = document.querySelector('.box')

    function updateCss(scale) {
      box.style.transform = `scale(${scale})`
    }

    let lastScale
    let currentScale

    let isAlreadyScaled = false
    const minScale = 1
    const maxScale = 1.8
    function handlePinch(e) {
      e.preventDefault()
      const isZooming = e.scale > 1


      if (isZooming) {
        if (!isAlreadyScaled) {
          lastScale = Math.min(minScale * e.scale, maxScale)
          isAlreadyScaled = true
        } else {
          lastScale = Math.min(minScale * (lastScale * e.scale), maxScale)
        }
      }

      updateCss(lastScale)
    }

    box.addEventListener('touchstart', e => {
      if (e.touches.length === 2) {
        handlePinch(e)
      }
    })

    box.addEventListener('touchmove', e => {
      if (e.touches.length === 2) {
        handlePinch(e)
      }
    })
* {
        box-sizing: border-box;
      }

      body {
        padding: 0;
        margin: 0;
      }

      .wrapper {
        height: 400px;
        width: 100%;
        top: 0;
        left: 0;
        position: relative;
        margin: 24px;
      }

      .scale-container {
        height: 100%;
        width: 100%;
        position: absolute;
        background: #eee;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .box {
        height: 200px;
        width: 200px;
        background: pink;
        position: absolute;
      }
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Home</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
  </head>
  <body>
    <div class="wrapper">
      <div class="scale-container">
        <div class="box"></div>
      </div>
    </div>
  </body>
</html>


from How to Incrementally Update an Elements Scale by Pinching with Js

No comments:

Post a Comment