今天在做一款微信小程序的时候才发现腾讯并没有提供微信上面的图像裁剪函数给开发者使用,想想要自己实现图像裁剪就头大,果断放弃这个方案。百度后发现了几款网友开发的插件,其中we-cropper最受大家欢迎,然而we-cropper也有缺陷,开发者只提供了固定裁剪方案,并不适合我,仍然记录下来,以备查询!
插件地址:https://github.com/we-plugin/we-cropper
文档地址:https://we-plugin.github.io/we-cropper/#/
引入到你的小程序中
两种方案,一种直接下载,手动复制,另一种是使用命令自动克隆
复制
cd my-project git clone https://github.com/we-plugin/we-cropper.git cd we-cropper
简单使用
wxml文件中,引入布局:
复制
<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>js文件中引入插件:
复制
import WeCropper from '../we-cropper/we-cropper.js'
const device = wx.getSystemInfoSync() // 获取设备信息
const width = device.windowWidth // 示例为一个与屏幕等宽的正方形裁剪框
const height = width
Page({
data: {
cropperOpt: {
id: 'cropper', // 用于手势操作的canvas组件标识符
targetId: 'targetCropper', // 用于用于生成截图的canvas组件标识符
pixelRatio: device.pixelRatio, // 传入设备像素比
width, // 画布宽度
height, // 画布高度
scale: 2.5, // 最大缩放倍数
zoom: 8, // 缩放系数
cut: {
x: (width - 200) / 2, // 裁剪框x轴起点
y: (width - 200) / 2, // 裁剪框y轴期起点
width: 200, // 裁剪框宽度
height: 200 // 裁剪框高度
}
}
}
})在页面onLoad函数中实例化WeCropper
复制
onLoad (option) {
const { cropperOpt } = this.data
this.cropper = new WeCropper(cropperOpt)
.on('ready', (ctx) => {
console.log(`wecropper is ready for work!`)
})
.on('beforeImageLoad', (ctx) => {
wx.showToast({
title: '上传中',
icon: 'loading',
duration: 20000
})
})
.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)
}给构造函数传入src参数即可使用。





评论 (0)