Vue 3实现的移动端两指控制图片缩放功能

2023-12-15 11:13:21

使用Vue 3的Composition API来实现的图片缩放功能。这是一个使用touch事件来实现的简单双指缩放图片的功能。

  1. 模板部分(Template)

    • <div>:这是一个相对定位的容器,同时设置overflow: hidden;以防止图片超出范围。这个元素监听了touchstarttouchmovetouchend事件。
    • <img>:这是要显示的图片,通过:style绑定动态的宽度。这个元素的引用被存储在image变量中,以便在脚本部分进行操作。
  2. 脚本部分(Script)

    • const image = ref(null);:创建一个引用(ref),用于存储图片元素的引用。
    • let initialDistance = 0;:初始化两个触摸点的初始距离。
    • let baseWidth = 100;:图片的初始宽度。
    • const imageWidth = ref(baseWidth);:创建一个引用,存储图片的宽度。
    • const onTouchStart = (event) => {...}:当双指触摸开始时,记录当前两个触摸点的距离。
    • const onTouchMove = (event) => {...}:当双指触摸移动时,计算当前两个触摸点的距离并与初始距离比较,根据比较结果调整图片的宽度。
    • const onTouchEnd = () => {...}:当双指触摸结束时,重置初始距离。

此代码示例在用户使用双指在屏幕上滑动时,会根据滑动的方向来放大或缩小图片的尺寸。其中,每次调整的幅度是10px,这个值可以根据实际需求进行调整。

<template>
  <div 
    style="position: relative; overflow: hidden;"
    @touchstart="onTouchStart"
    @touchmove="onTouchMove"
    @touchend="onTouchEnd"
  >
    <img 
      ref="image" 
      src="path_to_your_image.jpg" 
      alt="My Image" 
      :style="{ width: imageWidth + 'px' }"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue';

const image = ref(null);
let initialDistance = 0;
let baseWidth = 100; // 初始宽度
const imageWidth = ref(baseWidth);

const onTouchStart = (event) => {
  if (event.touches.length === 2) {
    initialDistance = Math.hypot(
      event.touches[0].pageX - event.touches[1].pageX,
      event.touches[0].pageY - event.touches[1].pageY
    );
  }
};

const onTouchMove = (event) => {
  if (event.touches.length === 2) {
    const currentDistance = Math.hypot(
      event.touches[0].pageX - event.touches[1].pageX,
      event.touches[0].pageY - event.touches[1].pageY
    );

    if (currentDistance > initialDistance) {
      // 放大图片
      imageWidth.value += 10;
    } else if (currentDistance < initialDistance) {
      // 缩小图片,可添加边界条件判断防止过小
      imageWidth.value -= 10;
    }

    initialDistance = currentDistance;
  }
};

const onTouchEnd = () => {
  initialDistance = 0;
};
</script>

文章来源:https://blog.csdn.net/m0_73481765/article/details/134937114
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。