最近使用了 Canvas 2D https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html https://developers.weixin.qq.com/miniprogram/dev/api/canvas/RenderingContext.html
这样一段代码,发现在本地运行是好的,但是总是有报警 Cannot read property 'scale' of undefined;at SelectorQuery callback function,这是为啥呢 canvas.getContext('2d') 文档也没说这个什么时候会获取不到 context
const query = this.createSelectorQuery();
query.select('#canvas-id')
.fields({ node: true, size: true })
.exec((res) => {
if (res && res[0] && res[0].node) {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
ctx.scale(2, 2);
}
});
楼主解决了吗?是什么原因?
猜测组件已经 detached 了,还在执行 exec 的回调,能获取到 node 节点,但是 getContext 不到值
wxml记得加上id='canvas-id'