使用Vue 3的Composition API来实现的图片缩放功能。这是一个使用touch事件来实现的简单双指缩放图片的功能。
模板部分(Template):
<div>
:这是一个相对定位的容器,同时设置overflow: hidden;
以防止图片超出范围。这个元素监听了touchstart
、touchmove
、touchend
事件。<img>
:这是要显示的图片,通过:style
绑定动态的宽度。这个元素的引用被存储在image
变量中,以便在脚本部分进行操作。
脚本部分(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>