微信小程序canvas转图片临时路径,使用wx.canvasToTempFilePath方法,官方文档中写了要在 draw() 回调里调用该方法才能保证图片导出成功。
然而,显示是写在draw()里面会报错draw is not a function,查阅了一下资料,新版 Canvas 2D 接口与 Web 一致,是没有 draw 方法的。https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.html
所以调wx.canvasToTempFilePath时不用写在draw里面,wx.canvasToTempFilePath的canvas参数的值不是canvas id了,而是canvas实例
参考代码:
rotatePic() {let that = this//获取canvasconst query = wx.createSelectorQuery()query.select('#myCanvas').fields({node: true,size: true}).exec(function(res) {const canvas = res[0].nodecanvas.width = that.canvasWidthcanvas.height = that.canvasHeightconst ctx = canvas.getContext('2d')const bg = canvas.createImage()bg.src = that.imgUrlbg.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//这个就是要的路径了}})}})}
参考文章:如何解决draw()报错 ctx.draw is not a function 的问题?
来源地址:https://blog.csdn.net/weixin_46687032/article/details/128819919