如何解决Canvas 2D使用canvasToTempFilePath?
onLoad() {
wx.createSelectorQuery()
.select('#cardCanvas')
.fields({
node: true,
size: true,
})
.exec(this.initCanvas.bind(this))
},
initCanvas(res) {
const width = res[0].width;
const height = res[0].height;
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = width * dpr;
canvas.height = height * dpr;
ctx.scale(dpr, dpr);
ctx.draw(false, () => {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width,
height,
destWidth: width,
destHeight: height,
canvasId: 'cardCanvas',
fileType: 'jpg',
quality: 1,
success(res) {
console.log(res.tempFilePath)
}
})
}
)
}
场景是在使用canvas2d时导出画布输出到图片,但是发现如下问题
1、使用canvas2d的上下文ctx调用draw()方法的时候报错:ctx.draw is not a function;at SelectorQuery callback function
2、canvasToTempFilePath的官方文档写着在 draw()
回调里调用该方法才能保证图片导出成功。文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasToTempFilePath.html
2 回复
你好,canvas2d不需要使用draw方法,参数传一个 canvas 对象可以使用 canvasToTempFilePath,具体可参考:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasToTempFilePath.html