VUE实现图片放大缩小,超出可滑动实现完整代码实现思路,监听手指触摸事件,保存坐标,然后计算2个触摸点的坐标是否符合放大缩小,如果符合的话调整zoomNum 可以修改放大缩小的颗粒度。
看示例代码:
<view class="block" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
<img :style="{zoom: zoom}" :src="provinceImg"></img>
</view>
JS
data:{
zoom: 1, //缩放
touchPoints: [], // 存储触摸点的数组
},
methods: {
onTouchStart(e) {
if (e.touches.length === 2) { // 确保有两个触摸点
this.touchPoints = e.touches.map(touch => ({
x: touch.clientX,
y: touch.clientY
}));
}
},
onTouchMove(e) {
let zoomNum =0.05;//放大缩小的颗粒度
if (e.touches.length === 2 && this.touchPoints.length === 2) {
const currentPoints = e.touches.map(touch => ({
x: touch.clientX,
y: touch.clientY
}));
const prevDistance = this.calculateDistance(this.touchPoints[0], this.touchPoints[1]);
const currentDistance = this.calculateDistance(currentPoints[0], currentPoints[1]);
if (currentDistance > prevDistance) {
// 放大
this.zoom = this.zoom + 0.05
console.log('Zoom in');
} else if (currentDistance < prevDistance) {
// 缩小
if (this.zoom > 1) {
this.zoom = this.zoom - 0.05
}
console.log('Zoom out');
}
this.touchPoints = currentPoints; // 更新触摸点坐标
}
},
onTouchEnd(e) {
// 处理触摸结束的逻辑
this.touchPoints = []; // 重置触摸点数组
},
}
CSS
.block {
position: relative;
width: 94%;
left: 3%;
height: 620rpx;
z-index: 9999;
overflow-x: scroll;
overflow-y: scroll;
}