jeudi 4 janvier 2018

How to zoom on a point with JavaScript?

My web project needs to zoom a div element around the mouse position as anchor while mouse wheeling, I was inspired by @Tatarize 's answer at Zoom in on a point (using scale and translate), but I can't implement it exactly, it can't zoom and translate around the mouse position, can any one help?

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" charset="utf-8">
        window.onload = () => {
            const STEP = 0.05;
            const MAX_SCALE = 10;
            const MIN_SCALE = 0.01;

            const red = document.getElementById('red');
            const yellow = red.parentNode;

            let scale = 1;

            yellow.onmousewheel = (event) => {
                event.preventDefault();
                
                let mouseX = event.clientX - yellow.offsetLeft - red.offsetLeft;
                let mouseY = event.clientY - yellow.offsetTop - red.offsetTop;

                const factor = event.wheelDelta / 120;

                const oldScale = scale;
                scale = scale * STEP * factor;
                scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale));

                const scaleChanged = scale - oldScale;
                const offsetX = -(mouseX * scaleChanged);
                const offsetY = -(mouseY * scaleChanged);

                console.log(offsetX, offsetY);

                red.style.transform = 'translate(' + offsetX + 'px, ' + offsetY + 'px)' + 'scale(' + scale + ')';
            }
        }
    </script>


    <style type="text/css">
        .yellow {
          background-color: yellow;
          width: 400px;
          height: 200px;
        }

        .red {
          background-color: red;
          width: 100px;
          height: 50px;
        }
    </style>


</head>

<body>

    <div class="yellow">
      <div id="red" class="red"></div>
    </div>

</body>
</html>

Aucun commentaire:

Enregistrer un commentaire