思路
- 点击上传图片,调用api wx.chooseImage() 获取到图片的本地临时文件路径列表
- 将获取的图片地址传入组件中,进行比例裁剪
- 获取裁剪之后的图片,上传到真实的资源地址
流程:
1.
下载组件(image-cropper) 详细操作步骤以及实现各种效果
链接: https://github.com/1977474741/image-cropper.
2.
"usingComponents": {
"image-cropper": "../component/image-cropper/image-cropper"
}
3.
<view style="width:100%;height:500rpx;">
<image-cropper id="image-cropper" bindload="cropperload" bindimageload="loadimage" bindtapcut="clickcut" limit_move="{{limit_move}}" disable_rotate="{{disable_rotate}}" width="{{width}}" height="{{height}}" imgSrc="{{src}}" angle="{{angle}}" disable_width="{{disable_width}}" max_width="{{max_width}}" max_height="{{max_height}}" disable_height="{{disable_height}}" disable_ratio="{{disable_ratio}}">
</image-cropper>
</view>
<view class='bottom'>
<button class="button" catchtap='upload'>上传</button>
<button bindtap='submit'>确定</button>
</view>
4.
.bottom {
position: absolute;
width: 100%;
bottom: 50rpx;
display: flex;
z-index: 10;
justify-content: center;
align-items: center;
flex-wrap: wrap;
height: 210rpx;
}
button {
font-size: 27rpx;
z-index: 2;
padding: 0 20rpx;
height: 60rpx;
min-width: 70rpx;
margin: 0 4rpx;
}
5.
//获取应用实例
const app = getApp()
Page({
data: {
src: '',
limit_move: true, //是否限制移动
},
onLoad: function (options) {
this.cropper = this.selectComponent("#image-cropper");
this.setData({
src: options.imgSrc
});
if (!options.imgSrc) {
this.cropper.upload(); //上传图片
}
},
loadimage(e) {
wx.hideLoading();
this.cropper.imgReset();
},
upload() {
let that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
wx.showLoading({
title: '加载中',
})
const tempFilePaths = res.tempFilePaths[0];
//重置图片角度、缩放、位置
that.cropper.imgReset();
that.setData({
src: tempFilePaths
});
}
})
},
submit() {
this.cropper.getImg((obj) => {
app.globalData.imgSrc = obj.url;
wx.navigateBack({
delta: -1
})
});
},
})
6.
注意:之前在项目中也过别的插件,但是存在兼容性问题,上传按钮会被覆盖导致无法上传