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

使用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>

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-12 01:18:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-12 01:18:04       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-12 01:18:04       82 阅读
  4. Python语言-面向对象

    2023-12-12 01:18:04       91 阅读

热门阅读

  1. 简单实用的firewalld命令

    2023-12-12 01:18:04       44 阅读
  2. 鸿蒙(HarmonyOS)应用开发——web组件

    2023-12-12 01:18:04       63 阅读
  3. leetcode第119场双周赛 - 2023 - 12 - 9

    2023-12-12 01:18:04       61 阅读
  4. Redis研学-认识与安装

    2023-12-12 01:18:04       50 阅读
  5. 力扣373. 查找和最小的 K 对数字

    2023-12-12 01:18:04       50 阅读
  6. 通义千问测试

    2023-12-12 01:18:04       55 阅读
  7. 使用OkHttp上传本地图片及参数

    2023-12-12 01:18:04       58 阅读
  8. 空间信息智能应用团队研究成果与人才引进

    2023-12-12 01:18:04       52 阅读
  9. Zookeeper面试题

    2023-12-12 01:18:04       60 阅读