Search code examples
javascripthtmljqueryzoomingpan

Reset scale to 1:1 after zoom


I wish to reset the image to its original zoom factor upon a button onclick() event.

It is the code for the onclick() event that I need.

I have the following div in my HTML:

div id="zoom">
    <img src="assets/img/map2.png" width="600" height="auto" alt="zoom">
</div>

And the following javascript allows for zoom-in, zoom-out, and click-and-drag.

<script>
 var scale = 1,
        panning = false,
        pointX = 0,
        pointY = 0,
        start = { x: 0, y: 0 },
        zoom = document.getElementById("zoom");

      function setTransform() {
        zoom.style.transform = "translate(" + pointX + "px, " + pointY + "px) scale(" + scale + ")";
      }

      zoom.onmousedown = function (e) {
        e.preventDefault();
        start = { x: e.clientX - pointX, y: e.clientY - pointY };
        panning = true;
      }

      zoom.onmouseup = function (e) {
        panning = false;
      }

      zoom.onmousemove = function (e) {
        e.preventDefault();
        if (!panning) {
          return;
        }
        pointX = (e.clientX - start.x);
        pointY = (e.clientY - start.y);
        setTransform();
      }

      zoom.onwheel = function (e) {
        e.preventDefault();
        var xs = (e.clientX - pointX) / scale,
          ys = (e.clientY - pointY) / scale,
          delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY);
        (delta > 0) ? (scale *= 1.2) : (scale /= 1.2);
        pointX = e.clientX - xs * scale;
        pointY = e.clientY - ys * scale;

        setTransform();
      }
      </script>

How can I reset the image to its original size, and re-center it, such as when the page loads initially?

Thank you.


Solution

  • You can call function resetImage() on your onClick event. The resetImage() function should look like this :

    function resetImage() {
      scale = 1;
      pointX = 0;
      pointY = 0;
      setTransform();
    }