uni-app 图片裁剪上传 vue3 vue2 均兼容 钉钉 微信
发布人:shili8
发布时间:2024-11-15 06:09
阅读次数:0
**图片裁剪上传组件**
在移动端开发中,图片裁剪上传是非常常见的需求。尤其是在微信、钉钉等社交平台上,用户需要裁剪并上传自己的头像或其他图片素材。在本文中,我们将介绍如何使用uni-app图形界面框架(类似于React Native)开发一个兼容Vue3和Vue2的图片裁剪上传组件。
**组件结构**
首先,我们需要定义组件的结构。我们将组件分为以下几个部分:
* **裁剪区域**:这是用户可以选择并裁剪图片的地方。
* **预览区域**:这是用户可以预览裁剪后的图片的地方。
* **上传按钮**:这是用户点击上传图片的地方。
**代码示例**
下面是组件的基本结构:
html<template>
<view class="image-cropper">
<!-- 裁剪区域 -->
<view class="cropper-container" @touchmove.prevent>
<image :src="imgUrl" mode="aspectFit" />
</view>
<!-- 预览区域 -->
<view class="preview-container">
<image :src="previewImg" mode="aspectFit" />
</view>
<!--上传按钮 -->
<button @click="uploadImage">上传</button>
</view>
</template>
<script>
export default {
data() {
return {
imgUrl: '', // 原始图片地址 previewImg: '', // 裁剪后的图片地址 }
},
methods: {
uploadImage() {
//上传裁剪后的图片 uni.uploadFile({
url: ' //上传接口 filePath: this.previewImg, // 裁剪后的图片路径 name: 'file',
success: (res) => {
console.log(res);
},
});
}
}
}
</script>
<style>
.image-cropper {
position: relative;
}
.cropper-container {
width:200px; /* 裁剪区域宽度 */
height:200px; /* 裁剪区域高度 */
border-radius:50%;
overflow: hidden;
}
.preview-container {
position: absolute;
top:100px;
left:100px;
}
</style>
**裁剪功能**
为了实现裁剪功能,我们需要使用uni-app提供的`@touchmove.prevent`事件来捕捉用户的手势操作。然后,我们可以根据手势操作的类型(如拖动、缩放等)进行相应的处理。
下面是裁剪功能的基本代码:
javascriptmethods: {
handleTouchMove(e) {
const { touches } = e;
const { clientX, clientY } = touches[0];
// 根据手势操作类型进行处理 if (e.type === 'touchmove') {
// 拖动 this.handleDrag(clientX, clientY);
} else if (e.type === 'touchend') {
// 缩放 this.handleScale(e.touches[0].clientX, e.touches[0].clientY);
}
},
handleDrag(x, y) {
const { cropperContainer } = this.$refs;
const rect = cropperContainer.getBoundingClientRect();
const { top, left } = rect;
// 根据拖动距离进行裁剪 if (x > left && x < left +200 && y > top && y < top +200) {
this.previewImg = `data:image/jpeg;base64,${this.imgUrl.substring(22)}?x=${x - left}&y=${y - top}`;
}
},
handleScale(x, y) {
const { cropperContainer } = this.$refs;
const rect = cropperContainer.getBoundingClientRect();
const { top, left } = rect;
// 根据缩放距离进行裁剪 if (x > left && x < left +200 && y > top && y < top +200) {
this.previewImg = `data:image/jpeg;base64,${this.imgUrl.substring(22)}?w=${Math.abs(x - left)}&h=${Math.abs(y - top)}`;
}
},
}
**上传功能**
最后,我们需要实现上传功能。我们可以使用uni-app提供的`uploadFile`方法来上传裁剪后的图片。
下面是上传功能的基本代码:
javascriptmethods: {
uploadImage() {
//上传裁剪后的图片 uni.uploadFile({
url: ' //上传接口 filePath: this.previewImg, // 裁剪后的图片路径 name: 'file',
success: (res) => {
console.log(res);
},
});
}
}
**总结**
在本文中,我们介绍了如何使用uni-app图形界面框架开发一个兼容Vue3和Vue2的图片裁剪上传组件。我们实现了裁剪功能、预览区域和上传按钮,并提供了基本代码示例和注释。

