帮我写一段微信小程序裁剪图片的裁剪器代码
时间: 2023-04-04 19:01:16 浏览: 205
好的,以下是微信小程序裁剪图片的裁剪器代码:
```javascript
Page({
data: {
src: '', // 图片路径
width: , // 图片宽度
height: , // 图片高度
cropperWidth: , // 裁剪框宽度
cropperHeight: , // 裁剪框高度
cropperLeft: , // 裁剪框左边距
cropperTop: , // 裁剪框上边距
scale: 1, // 图片缩放比例
angle: , // 图片旋转角度
cropperData: {}, // 裁剪框数据
showCropper: false, // 是否显示裁剪框
showPreview: false, // 是否显示预览图
previewImage: '', // 预览图路径
},
// 选择图片
chooseImage() {
wx.chooseImage({
success: (res) => {
const tempFilePaths = res.tempFilePaths
this.setData({
src: tempFilePaths[],
})
this.getImageInfo()
},
})
},
// 获取图片信息
getImageInfo() {
wx.getImageInfo({
src: this.data.src,
success: (res) => {
const { width, height } = res
const cropperWidth = width > height ? height : width
const cropperHeight = cropperWidth
const cropperLeft = (width - cropperWidth) / 2
const cropperTop = (height - cropperHeight) / 2
this.setData({
width,
height,
cropperWidth,
cropperHeight,
cropperLeft,
cropperTop,
showCropper: true,
})
},
})
},
// 裁剪框数据变化
cropperChange(e) {
this.setData({
cropperData: e.detail,
})
},
// 点击取消
cancel() {
this.setData({
showCropper: false,
showPreview: false,
})
},
// 点击确定
confirm() {
wx.showLoading({
title: '正在生成图片...',
})
const { cropperData, src, width, height, angle } = this.data
const canvasWidth = cropperData.width
const canvasHeight = cropperData.height
const canvasLeft = cropperData.left - this.data.cropperLeft
const canvasTop = cropperData.top - this.data.cropperTop
const canvasId = 'cropperCanvas'
const ctx = wx.createCanvasContext(canvasId, this)
ctx.clearRect(, , canvasWidth, canvasHeight)
ctx.save()
ctx.translate(canvasWidth / 2, canvasHeight / 2)
ctx.rotate((angle * Math.PI) / 180)
ctx.drawImage(src, -width / 2 + canvasLeft, -height / 2 + canvasTop, width, height)
ctx.restore()
ctx.draw(false, () => {
wx.canvasToTempFilePath({
canvasId,
success: (res) => {
wx.hideLoading()
this.setData({
showCropper: false,
showPreview: true,
previewImage: res.tempFilePath,
})
},
}, this)
})
},
// 点击旋转
rotate() {
const angle = this.data.angle + 90
this.setData({
angle,
})
},
// 点击缩小
zoomOut() {
const scale = this.data.scale - .1
this.setData({
scale,
})
},
// 点击放大
zoomIn() {
const scale = this.data.scale + .1
this.setData({
scale,
})
},
})
```
希望这段代码能够帮到你!
阅读全文