2

So I have a header.. and an image. On tablet I want to be able to pinch and zoom into the image but i'm struggling. I've looked at other similar questions. But as I'm still learning, i'm not fully sure what is going wrong for me too fix.

<div class="header">
      <h1><img src="logo.png" alt="">Title</h1>
      <ul>
        <li>Test</li>
        <li>Test</li>
        <li>Test</li>
      </ul>
    </div>


    <div id="map">
      <div>
        <img src="bg.png" alt="" width="1200" id="mapImage">
      </div>
    </div>

    <script src="https://hammerjs.github.io/dist/hammer.js"></script>

Below is my Javascript i'm using to try and get the pinch and zoom working correctly. I'm using hammer.js for this.

<script>
  var hammertime = Hammer(document.getElementById('map'), {
    transform_always_block: true,
    transform_min_scale: 1,
    drag_block_horizontal: false,
    drag_block_vertical: false,
    drag_min_distance: 0
  });

  var rect = document.getElementById('mapImage');

  var posX=0, posY=0,
      scale=1, last_scale,
      last_posX=0, last_posY=0;

  hammertime.on('touch drag transform dragend', function(ev) {
    console.log(ev);
      switch(ev.type) {
          case 'touch':
              last_scale = scale;
              break;

          case 'drag':
              posX = last_posX + ev.gesture.deltaX;
              posY = last_posY + ev.gesture.deltaY;
              break;

          case 'transform':
              scale = Math.max(1, Math.min(last_scale * ev.gesture.scale, 10));
              break;
          case 'dragend':
              last_posX = posX;
              last_posY = posY;
              break;
      }

      // transform!
      var transform = "";
      if(scale > 1){
          transform =
              "translate3d("+posX+"px,"+posY+"px, 0) " +
              "scale3d("+scale+","+scale+", 0) ";
      }else{
          transform =
              "translate3d(0, 0, 0) " +
              "scale3d(1, 1, 0) ";
          posX = 0;
          posY = 0;
          last_posX = 0;
          last_posY = 0;
      }

      rect.style.transform = transform;
      rect.style.oTransform = transform;
      rect.style.msTransform = transform;
      rect.style.mozTransform = transform;
      rect.style.webkitTransform = transform;
  });
</script>

Thanks for help!

1 Answer 1

0

I have done similarly in one page. PFB my code:

var scale = 1;
var myElement = document.getElementById('map');

var hammertime = new Hammer(myElement);
hammertime.get('pinch').set({enable: true});

hammertime.on("pinchin", function(e) {
    scale -= 0.02;
    $('#map img').css('zoom', scale);
});

hammertime.on("pinchout", function(e) {
    scale += 0.02;
    $('#map img').css('zoom', scale);
});

Please let me know if you need any more information.

Not the answer you're looking for? Browse other questions tagged or ask your own question.