uniapp实现图片剪裁
时间: 2023-10-01 16:07:08 浏览: 85
Uniapp提供了一个uni-cropper组件,可以方便地实现图片剪裁功能。
首先,在需要使用图片剪裁的页面中引入uni-cropper组件:
```
<template>
<view>
<uni-cropper
:src="src"
:aspect-ratio="aspectRatio"
:output-size="outputSize"
@cropperdone="cropperDone"
/>
</view>
</template>
<script>
export default {
data() {
return {
src: '', // 待剪裁的图片路径
aspectRatio: 1, // 剪裁框宽高比
outputSize: [300, 300], // 输出图片的大小
}
},
methods: {
cropperDone(res) {
console.log(res) // 输出剪裁后的图片信息,包括路径、宽高、大小等
}
}
}
</script>
```
其中,src属性表示待剪裁的图片路径,aspectRatio属性表示剪裁框的宽高比,outputSize属性表示输出图片的大小。
在页面中添加uni-cropper组件后,需要在methods中添加一个cropperDone方法,该方法会在剪裁完成后触发,并返回剪裁后的图片信息,包括路径、宽高、大小等。
最后,在页面中触发图片剪裁事件,调用uni-cropper组件的方法进行剪裁:
```
this.$refs.cropper.show()
```
其中,$refs.cropper表示uni-cropper组件的引用,show方法会弹出图片剪裁框。
完整的图片剪裁示例代码如下:
```
<template>
<view>
<image
:src="src"
mode="aspectFit"
style="width: 100%; height: 300rpx;"
/>
<button @tap="showCropper">剪裁</button>
<uni-cropper
ref="cropper"
:src="src"
:aspect-ratio="aspectRatio"
:output-size="outputSize"
@cropperdone="cropperDone"
/>
</view>
</template>
<script>
export default {
data() {
return {
src: 'https://img.yzcdn.cn/upload_files/2021/06/11/Fkx6GQv6rWU6m1UJwFbMvZvY8ZjC.jpg',
aspectRatio: 1,
outputSize: [300, 300],
}
},
methods: {
showCropper() {
this.$refs.cropper.show()
},
cropperDone(res) {
console.log(res)
this.src = res.tempFilePath // 将剪裁后的图片替换原图片
}
}
}
</script>
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)