新建文件
在utils新建名为“we-cropper.js”的文件
index.js
开头引用
import WeCropper from '../../utils/we-cropper.js'
const device = wx.getSystemInfoSync()
const _rpx = device.windowWidth / 750
const width = 160 * _rpx; //裁剪框宽度
const height = 160 * _rpx; //裁剪框高度
复制代码
文中使用
Page({
data: {
cropperOpt: {
id: 'cropper',
width,
height,
scale: 2.5,
zoom: 8,
cut: {
x: 0,
y: 0,
width: width,
height: height
}
}
},
touchStart(e) {
this.wecropper.touchStart(e)
},
touchMove(e) {
this.wecropper.touchMove(e)
},
touchEnd(e) {
this.wecropper.touchEnd(e)
},
onLoad: function(options) {
let that = this;
const {
cropperOpt
} = this.data
new WeCropper(cropperOpt)
.on('ready', (ctx) => {
console.log(`wecropper is ready for work!`)
})
.on('beforeImageLoad', (ctx) => {
console.log(`before picture loaded, i can do something`)
wx.showToast({
title: '上传中',
icon: 'loading',
duration: 1000
})
})
.on('imageLoad', (ctx) => {
console.log(`picture loaded`)
wx.hideToast()
})
.on('beforeDraw', (ctx, instance) => {
console.log(`before canvas draw,i can do something`)
})
.updateCanvas();
},
chooseImage() {
let that = this;
wx.chooseImage({
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
that.wecropper.pushOrign(res.tempFilePaths[0]);
},
})
},
getCropperImage() {
let that = this;
that.wecropper.getCropperImage((src) => {
if (src) {
//此处添加用户确定裁剪后执行的操作 src是截取到的图片路径
wx.getFileSystemManager().readFile({
filePath: src, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
that.setData({
userImageBase64: 'data:image/png;base64,' + res.data,
noHeadImageBase64: res.data
})
},
})
}
}
}
})
复制代码
index.wxml
<template name="we-cropper">
<canvas disable-scroll="true" bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd" style="width:{{width}}px;height:{{height}}px;z-index:1;" canvas-id="{{id}}" hidden='{{canvasTag}}'>
</canvas>
</template>
<template is="we-cropper" data="{{...cropperOpt}}" />
复制代码