uniapp手机双指缩放功能如何实现

在uniapp中如何实现手机双指缩放功能?希望能提供一个具体的代码示例,包括手势识别的实现方法和缩放效果的绑定方式。目前尝试过使用touch事件但效果不太理想,是否有更简便的解决方案?最好能兼容H5和APP端。

2 回复

在uniapp中,可通过@touchstart@touchmove等事件监听双指触摸,计算两点间距离变化实现缩放。使用event.touches获取触摸点坐标,通过距离差判断缩放比例,并调整元素样式或canvas绘制比例。


在 UniApp 中实现双指缩放功能,可以通过监听触摸事件(touchstarttouchmove)计算两点间距离变化来实现。以下是具体步骤和示例代码:

实现步骤:

  1. 监听触摸事件:在元素上绑定 @touchstart@touchmove 事件。
  2. 记录触摸点:在 touchstart 时记录初始两指位置。
  3. 计算距离变化:在 touchmove 时实时计算两点间距离,并与初始距离比较,得到缩放比例。
  4. 应用缩放:通过 CSS transform: scale() 或修改元素宽高实现视觉缩放。

示例代码(Vue 模板):

<template>
  <view 
    class="zoom-container"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    :style="{ transform: `scale(${scale})` }"
  >
    <!-- 可缩放的内容 -->
    <image src="/static/example.jpg" mode="widthFix"></image>
  </view>
</template>

<script>
export default {
  data() {
    return {
      scale: 1, // 初始缩放比例
      startDistance: 0, // 初始两指距离
    };
  },
  methods: {
    // 触摸开始
    handleTouchStart(e) {
      if (e.touches.length >= 2) {
        // 计算初始两指距离
        this.startDistance = this.getDistance(
          e.touches[0],
          e.touches[1]
        );
      }
    },
    // 触摸移动
    handleTouchMove(e) {
      if (e.touches.length >= 2) {
        e.preventDefault(); // 阻止默认行为(如页面滚动)
        
        // 计算当前两指距离
        const currentDistance = this.getDistance(
          e.touches[0],
          e.touches[1]
        );
        
        // 计算缩放比例(可调整灵敏度)
        if (this.startDistance > 0) {
          const scale = currentDistance / this.startDistance;
          this.scale = Math.max(0.5, Math.min(scale * this.scale, 3)); // 限制缩放范围
        }
        
        // 更新初始距离为当前距离,实现连续缩放
        this.startDistance = currentDistance;
      }
    },
    // 计算两点间距离(勾股定理)
    getDistance(touch1, touch2) {
      const dx = touch2.clientX - touch1.clientX;
      const dy = touch2.clientY - touch1.clientY;
      return Math.sqrt(dx * dx + dy * dy);
    },
  },
};
</script>

<style>
.zoom-container {
  /* 确保元素可交互且居中 */
  touch-action: none;
  transform-origin: center;
}
</style>

注意事项:

  • 缩放范围:通过 Math.max()Math.min() 限制缩放比例(示例为 0.5~3 倍)。
  • 性能优化:复杂内容缩放可能卡顿,建议对图片或简单元素使用。
  • 手势冲突:若页面需滚动,可在特定区域禁用默认事件(如 @touchmove.prevent)。

扩展建议:

  • 可结合 gesture 插件(如 uni-gesture)简化实现。
  • 需重置缩放状态时,在 touchend 事件中重置 startDistance 为 0。

以上代码可直接在 UniApp 项目中测试使用,根据实际需求调整参数即可。

回到顶部