<canvas class="edit-question-canvas" type="2d" id="canvasCuteImage"></canvas>
/*
.edit-question-canvas {
position: absolute;
left: -750rpx;
width: 690rpx;
height: 100rpx;
}
样式随便自己写
*/
// 使用方法
let path = await this.canvasCuteImageExecute(item.data.path, 690, item.data.rect, '#canvasCuteImage', this.pxRatio)
/*
path:本地图片的地址
w: 截取后图片的宽度
rect:[x,y,width,height] 解决的矩形范围
canvasId:canvas id
pxRatio:rpx 转 px 的比例
onLoad() {
let that = this
uni.getSystemInfo({
success: function(res) {
that.pxRatio = res.windowWidth / 750
}
})
},
*/
canvasCuteImageExecute(path, w, rect, canvasId, pxRatio) {
return new Promise((resolve, reject) => {
let canvasHeight = Math.floor(w * rect[3] / rect[2])
let x = rect[0]
let y = rect[1]
let width = rect[2]
let height = rect[3]
let destWidth = w * pxRatio
let destHeight = canvasHeight * pxRatio
const query = wx.createSelectorQuery()
query.select(canvasId)
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
canvas.width = destWidth
canvas.height = destHeight
let image = canvas.createImage(); //创建image实例
image.src = path
image.onload = function() {
ctx.drawImage(image, x, y, width, height, 0, 0, destWidth, destHeight);
wx.canvasToTempFilePath({
canvas: canvas,
success(res) {
// console.log(res.tempFilePath);
resolve(res.tempFilePath)
},
fail(err) {
console.log(err)
resolve('')
}
})
}
})
})
// 计算 canvas 的高度
},