多点触控手势怎么监听 pinch 缩放?

迷人的国凤 阅读 4

我在做一个移动端图片查看器,想支持双指缩放,但不知道怎么正确监听 pinch 手势。试过 touchstart 和 touchmove,但自己算距离变化很麻烦,而且容易误触发。

看到有些库比如 Hammer.js 能直接用 pinch 事件,但项目不想引入额外依赖。有没有原生 JS 的简洁实现方式?

目前我这样写,但缩放时页面会抖动,而且两个手指移动不同步就失效了:

let startDistance = 0;
element.addEventListener('touchstart', (e) => {
  if (e.touches.length === 2) {
    const dx = e.touches[0].pageX - e.touches[1].pageX;
    const dy = e.touches[0].pageY - e.touches[1].pageY;
    startDistance = Math.sqrt(dx * dx + dy * dy);
  }
});
element.addEventListener('touchmove', (e) => {
  if (e.touches.length === 2) {
    const dx = e.touches[0].pageX - e.touches[1].pageX;
    const dy = e.touches[0].pageY - e.touches[1].pageY;
    const currentDistance = Math.sqrt(dx * dx + dy * dy);
    const scale = currentDistance / startDistance;
    // 应用 scale 到图片...
  }
});
我来解答 赞 0 收藏
二维码
手机扫码查看
暂无解答

暂无解答