2 回复
小程序自带的图片预览就可以
在处理uni-app小程序中的手势缩放图片功能时,你可以利用canvas
组件结合手势监听事件来实现。以下是一个简化的代码案例,展示了如何实现这一功能。
1. 在页面的.vue
文件中
<template>
<view class="container">
<canvas
canvas-id="imageCanvas"
style="width: 100%; height: 100%;"
/>
<image
src="/static/your-image.jpg"
style="display: none;"
@load="onLoadImage"
ref="sourceImage"
/>
</view>
</template>
<script>
export default {
data() {
return {
scale: 1,
lastScale: 1,
lastX: 0,
lastY: 0,
originX: 0,
originY: 0,
imageInfo: {}
};
},
methods: {
onLoadImage(e) {
this.imageInfo = e.detail;
this.drawImage();
},
drawImage() {
const ctx = uni.createCanvasContext('imageCanvas');
ctx.clearRect(0, 0, this.imageInfo.width, this.imageInfo.height);
ctx.drawImage(
this.$refs.sourceImage.dataset.src,
0,
0,
this.imageInfo.width,
this.imageInfo.height,
0,
0,
this.imageInfo.width * this.scale,
this.imageInfo.height * this.scale
);
ctx.draw();
},
onTouchStart(e) {
this.lastX = e.touches[0].x;
this.lastY = e.touches[0].y;
this.originX = this.lastX - (this.imageInfo.width * this.scale / 2);
this.originY = this.lastY - (this.imageInfo.height * this.scale / 2);
},
onTouchMove(e) {
const currentX = e.touches[0].x;
const currentY = e.touches[0].y;
this.originX += currentX - this.lastX;
this.originY += currentY - this.lastY;
this.lastX = currentX;
this.lastY = currentY;
this.drawImage();
},
onTouchEnd(e) {
// Handle pinch to zoom
if (e.touches.length === 2) {
const currentScale = this.calculateDistance(e.touches[0], e.touches[1]) / this.lastScale;
this.scale *= currentScale / this.lastScale;
this.lastScale = this.calculateDistance(e.touches[0], e.touches[1]);
this.drawImage();
}
},
calculateDistance(touch1, touch2) {
const dx = touch2.x - touch1.x;
const dy = touch2.y - touch1.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
};
</script>
<style>
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
</style>
2. 注意事项
- 在
<image>
标签中使用@load
事件来确保图片加载完成后再获取其尺寸。 - 使用
canvas
组件绘制图片,并通过手势事件(touchstart
、touchmove
、touchend
)来实现图片的平移和缩放。 calculateDistance
函数用于计算两点之间的距离,这在处理双指缩放时非常有用。- 样式部分仅用于居中显示
canvas
,你可以根据需求进行调整。
这段代码提供了一个基本的手势缩放图片的实现,适用于uni-app小程序开发。你可以根据实际需求进一步优化和扩展功能。