+
95
-

回答

在 UniApp 中实现类似抖音的双指缩放和移动视频的效果,可以通过使用 uni-app 提供的 video 组件结合 touch 事件来实现。以下是一个简单的示例代码,展示了如何实现这一功能:

首先,确保你已经在 pages.json 中配置了视频页面的路由。

在你的视频页面中,使用 video 组件并绑定 touch 事件来处理缩放和移动。

<template>
  <view class="container">
    <video id="myVideo" class="video" :src="videoSrc" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"></video>
  </view>
</template>

<script>
export default {
  data() {
    return {
      videoSrc: 'your_video_url_here',
      touchStart: { x: 0, y: 0, time: 0 },
      scale: 1,
      translateX: 0,
      translateY: 0,
      lastTouchDistance: 0
    };
  },
  methods: {
    handleTouchStart(event) {
      if (event.touches.length === 1) {
        this.touchStart.x = event.touches[0].pageX;
        this.touchStart.y = event.touches[0].pageY;
        this.touchStart.time = Date.now();
      } else if (event.touches.length === 2) {
        this.lastTouchDistance = this.getTouchDistance(event.touches);
      }
    },
    handleTouchMove(event) {
      if (event.touches.length === 1) {
        const deltaX = event.touches[0].pageX - this.touchStart.x;
        const deltaY = event.touches[0].pageY - this.touchStart.y;
        this.translateX += deltaX;
        this.translateY += deltaY;
        this.applyTransform();
        this.touchStart.x = event.touches[0].pageX;
        this.touchStart.y = event.touches[0].pageY;
      } else if (event.touches.length === 2) {
        const touchDistance = this.getTouchDistance(event.touches);
        const deltaScale = touchDistance / this.lastTouchDistance;
        this.scale *= deltaScale;
        this.lastTouchDistance = touchDistance;
        this.applyTransform();
      }
    },
    handleTouchEnd(event) {
      // Reset touch start data
      this.touchStart = { x: 0, y: 0, time: 0 };
    },
    getTouchDistance(touches) {
      const dx = touches[0].pageX - touches[1].pageX;
      const dy = touches[0].pageY - touches[1].pageY;
      return Math.sqrt(dx * dx + dy * dy);
    },
    applyTransform() {
      const video = document.getElementById('myVideo');
      video.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
    }
  }
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.video {
  width: 100%;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
</style>
解释

模板部分

使用 video 组件,并绑定 touchstart、touchmove 和 touchend 事件。

脚本部分

handleTouchStart:记录触摸开始的位置和时间,如果是双指触摸,则计算初始双指间距。handleTouchMove:处理单指移动和双指缩放。单指移动时,计算移动的距离并更新 translateX 和 translateY;双指缩放时,计算缩放比例并更新 scale。handleTouchEnd:重置触摸开始的数据。getTouchDistance:计算双指之间的距离。applyTransform:应用变换到视频元素上。

样式部分

设置容器为全屏,并使视频居中显示。

网友回复

我知道答案,我要回答