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
你好,怎么获取canvas组件实例?
const query = wx.createSelectorQuery();
const canvasObj = await new Promise((resolve, reject) => {
query.select('#posterCanvas')
.fields({ node: true, size: true })
.exec(async (res) => {
resolve(res[0].node);
})
});
console.log(canvasObj);
wx.canvasToTempFilePath({
//fileType: 'jpg',
//canvasId: 'posterCanvas', //之前的写法
canvas: canvasObj, //现在的写法
success: (res) => {},
fail(res) {
console.log(res);
}
}, this)
这是我写的文章
https://developers.weixin.qq.com/community/develop/article/doc/000242073903a04e082ab595b52013
你好,canvas2d不需要使用draw方法,参数传一个 canvas 对象可以使用 canvasToTempFilePath,具体可参考:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasToTempFilePath.html
this.canvasToTempFilePath({
canvas,
destWidth: this.data.width * (wx.getSystemInfoSync().pixelRatio / 2),
destHeight: this.data.height * (wx.getSystemInfoSync().pixelRatio / 2),
success: (res) => {
resolve(res.tempFilePath);
},
fail: (e) => {
reject(e);
},
});
_init(res) {
canvasAy = res[0].node
this.ctx = canvasAy.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvasAy.width = res[0].width * dpr
canvasAy.height = res[0].height * dpr
this.ctx.scale(dpr, dpr)
this.draw();
this.canvasToTempFilePath({
canvasAy,
destWidth: this.data.width * (wx.getSystemInfoSync().pixelRatio / 2),
destHeight: this.data.height * (wx.getSystemInfoSync().pixelRatio / 2),
success: (res) => {
resolve(res.tempFilePath);
console.log(res.tempFilePath);
},
fail: (e) => {
reject(e);
},
});
错误已经提示了,ctx.draw不是一个function,用法错误:
this.ctx = wx.createCanvasContext('你的canvasId');
this.ctx.draw...