The WeChat applet canvas transfers the temporary path of the picture, using the wx.canvasToTempFilePath method. The official document states that this method must be called in the draw() callback to ensure that the picture is exported successfully.
However, it shows that if it is written in draw(), it will report an error that draw is not a function. After checking the information, the new version of Canvas 2D interface is consistent with the Web, and there is no draw method. https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.html
So when adjusting wx.canvasToTempFilePath, you don’t need to write it in draw. The value of the canvas parameter of wx.canvasToTempFilePath is not the canvas id, but the canvas instance
Reference Code:
rotatePic() {
let that = this
//获取canvas
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec(function(res) {
const canvas = res[0].node
canvas.width = that.canvasWidth
canvas.height = that.canvasHeight
const ctx = canvas.getContext('2d')
const bg = canvas.createImage()
bg.src = that.imgUrl
bg.onload = () => {
//先保存一下设置
ctx.save();
//将画布向右下移动一半宽
ctx.translate(canvas.width / 2, canvas.height / 2);
//再旋转角度:逆时针旋转180度
ctx.rotate(-180 / 180 * Math.PI);
//最后将画布移回来,摆正之前的位置
ctx.translate(-canvas.width / 2, -canvas.height / 2);
//最后画出来
ctx.drawImage(bg, 0, 0);
//不要忘记恢复之前的设置
ctx.restore()
//canvas转文件的临时路径 (本地路径)
wx.canvasToTempFilePath({
canvas,
fileType: "jpg",
quality: 1,
success: (res) => {
that.imgUrl = res.tempFilePath//这个就是要的路径了
}
})
}
})
}
Reference article: How to solve the problem that draw() reports ctx.draw is not a function?