相应地检测捏和缩放图像

时间:2017-09-11 06:17:53

标签: javascript javascript-events touch

如何检测启用触摸的设备上的捏合并使用它仅使用javascript操作元素/图像。

1 个答案:

答案 0 :(得分:0)

使用dom和触摸事件。

HTML

<div id="wrapper" style="width:100%;overflow:auto;">
<img src="https://tenfizz.com/wp-content/uploads/2017/07/Untitled-1024x538.png" id="target-image" style="display:block;width:100%;transition:0.1s linear all;position:relative;transform-origin:0 0;transform:scale(1)">
</div>

的Javascript

 //set the elements
 var wrapper = document.getElementById("wrapper");
 var timg = document.getElementById("target-image") , rs = 1;

 //to retrive the pinch e
 function dist(a) {
    var zw = a.touches[0].pageX - a.touches[1].pageX, zh = a.touches[0].pageY - a.touches[1].pageY;
    return Math.sqrt(zw * zw + zh * zh);
  }

  //attach the events
  wrapper.addEventListener('touchstart', function(event) {
    if (event.touches.length > 1) {
      event.preventDefault();
      d1 = dist(event);
    }
  });
  wrapper.addEventListener('touchmove', function(event) {
    if (event.touches.length > 1) {
      event.preventDefault();

      //get the ratio
      rf = dist(event) / d1 * rs;
      timg.style.transform = "scale(" + rf + ")";
    }
  });

  //check if scale is less than 1 and keep the previous ratio
  wrapper.addEventListener('touchend', function() {
    rf < 1 ? (timg.style.transform = "scale(1)", rs = 1) : rs = rf;
  });