// 图片拆剪
clipImage(src, imgW, imgH, cb) {
// ‘canvas’为前面创建的canvas标签的canvas-id属性值
let ctx = wx.createCanvasContext('canvas')
let canvasW = 640,
canvasH = imgH
if (imgW / imgH > 5 / 4) {
// 长宽比大于5:4
canvasW = (imgH * 5) / 4
} // 将图片绘制到画布
ctx.drawImage(
src,
(imgW - canvasW) / 2,
0,
canvasW,
canvasH,
0,
0,
canvasW,
canvasH
)
// draw()必须要用到,并且需要在绘制成功后导出图片
ctx.draw(false, () => {
// 导出图片
wx.canvasToTempFilePath({
width: canvasW,
height: canvasH,
destWidth: canvasW,
destHeight: canvasH,
canvasId: 'canvas',
fileType: 'jpg',
success: res => {
// res.tempFilePath为导出的图片路径
typeof cb == 'function' && cb(res.tempFilePath)
}
})
})
},
使用,因为小程序只允许https,所以转换了一下
wx.getImageInfo({
src: res.result.headImage.replace('http', 'https'),
success: res => {
// 这个是我封装的裁剪图片方法(下面将会说到)
that.clipImage(res.path, res.width, res.height, img => {
that.setData({
shareUrl: img
})
})
}
})