小程序涉及到了用户上传头像的功能,用户可以手动选择裁剪区域。
(1)上传头像页面
选择图片,将得到的src地址传递到图片裁剪页面
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function(res) {
const src = res.tempFilePaths[0];
wx.navigateTo({
url: '../upload/upload?src=' + src
})
},
})
(2)图片裁剪页面
1、引入we-cropper.wxml,主要为了置入canvas作为图片裁剪的容器
<import src='/we-cropper/we-cropper.wxml'/>
<view class="cropper-wrapper">
<template is="we-cropper" data="{{...cropperOpt}}"/>
<view class="cropper-buttons">
<view
class="upload"
bindtap="uploadTap">
上传图片
</view>
<view
class="getCropperImage"
bindtap="getCropperImage">
生成图片
</view>
</view>
</view>
2、引入we-cropper.js
import WeCropper from '../../../we-cropper/we-cropper.js';
const device = wx.getSystemInfoSync() // 获取设备信息
const width = device.windowWidth // 示例为一个与屏幕等宽的正方形裁剪框
const height = device.windowHeight + 10
Page({
data: {
cropperOpt: {
id: 'cropper', // 用于手势操作的canvas组件标识符
targetId: 'targetCropper', // 用于用于生成截图的canvas组件标识符
pixelRatio: device.pixelRatio, // 传入设备像素比
width, // 画布宽度
height, // 画布高度
src: '',
scale: 2.5, // 最大缩放倍数
zoom: 8, // 缩放系数
cut: {
x: (width - 320) / 2, // 裁剪框x轴起点
y: (width - 320) / 2, // 裁剪框y轴起点
width: 320, // 裁剪框宽度
height: 320 // 裁剪框高度
}
}
},
// 页面onLoad函数中实例化WeCropper
onLoad: function(options) {
const {
cropperOpt
} = this.data;
cropperOpt.src = options.src;
if (cropperOpt.src) {
this.cropper = new WeCropper(cropperOpt)
.on('ready', (ctx) => {
console.log(`wecropper is ready for work!`)
})
.on('beforeImageLoad', (ctx) => {
wx.showToast({
title: '上传中',
icon: 'loading',
duration: 3000
})
})
.on('imageLoad', (ctx) => {
wx.hideToast()
})
}
},
// 插件通过touchStart、touchMove、touchEnd方法来接收事件对象。
touchStart(e) {
this.cropper.touchStart(e)
},
touchMove(e) {
this.cropper.touchMove(e)
},
touchEnd(e) {
this.cropper.touchEnd(e)
},
// 自定义裁剪页面的布局中,可以重新选择图片
uploadTap() {
const self = this
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success(res) {
const src = res.tempFilePaths[0]
self.cropper.pushOrign(src)
}
})
},
// 生成图片
getCropperImage()
this.cropper.getCropperImage(tempFilePath => {
// tempFilePath 为裁剪后的图片临时路径
if (tempFilePath) {
// 拿到裁剪后的图片路径的操作
}else{
console.log('获取图片地址失败,请稍后重试')
}
})
}
})
注:we-cropper插件:https://we-plugin.github.io/we-cropper/#/