uni-app topWindow 放canvas 提示 TypeError: Cannot read property 'id' of undefined

uni-app topWindow 放canvas 提示 TypeError: Cannot read property ‘id’ of undefined

示例代码:

topWindow页面代码:

<canvas canvas-id="test_canvas" style="background-color: #ff0;width:100px;height:50px;"></canvas>

js代码

mounted() {  
    setTimeout(() => {  
        let ctx = uni.createCanvasContext('test_canvas');  
        ctx.setFillStyle('red');  
        ctx.fillRect(0, 0, 20, 20);  
        ctx.restore();  

        ctx.draw(false,() => {  
            console.log('topWindow绘画成功');  
        });  
    }, 1000);  
},

page-index的页面代码:

<canvas canvas-id="test_page_canvas" style="background-color: #ff0;width:100px;height:50px;"></canvas>

js代码

onReady() {  
    setTimeout(() => {  
        let ctx = uni.createCanvasContext('test_page_canvas');  
        ctx.setFillStyle('red');  
        ctx.fillRect(0, 0, 20, 20);  
        ctx.restore();  

        ctx.draw(false,() => {  
            console.log('Page绘画成功');  
        });  
    }, 1000);  
},

### 操作步骤:


只要topWindow放了canvas组件,刷新页面就会提示错误,删掉重新刷新页面就正常

预期结果:

想要topWindow可以正常使用canvas组件画图


### 实际结果:


报TypeError: Cannot read property 'id' of undefined错误,canvas组件api没有报错ctx.draw能正常回调,但是画布内容没有显示出来

bug描述:

只要topWindow放了canvas组件,就会提示错误信息,而且画图也没效果,删掉topWindow里的canvas重新刷新页面就不会报错,使用组件引入也是一样的问题。

而mainWindow里页面上的canvas组件可以正常使用


| 项目 | 信息 |
| --- | --- |
| 产品分类 | uniapp/H5 |
| PC开发环境操作系统 | Windows |
| PC开发环境操作系统版本号 | w7 |
| HBuilderX类型 | Alpha |
| HBuilderX版本号 | 3.1.14 |
| 浏览器平台 | Chrome |
| 浏览器版本 | 88.0.4324.190(正式版本) (64 位) |
| 项目创建方式 | HBuilderX |

![](https://www.itying.com/uniimg.php?url=https://img-cdn-tc.dcloud.net.cn/uploads/questions/20210512/d2a0afef3195e891f551b13ef0e83d67.png)

更多关于uni-app topWindow 放canvas 提示 TypeError: Cannot read property 'id' of undefined的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

你好,后来怎么解决的啊,我这边也遇到了

更多关于uni-app topWindow 放canvas 提示 TypeError: Cannot read property 'id' of undefined的实战教程也可以访问 https://www.itying.com/category-93-b0.html


这是一个已知的uni-app框架在H5平台上的兼容性问题。在topWindow中使用canvas组件时,由于框架初始化时序问题,canvas上下文创建时无法正确获取到节点信息,导致uni.createCanvasContext方法内部读取不到canvas节点的id属性。

问题分析:

  1. topWindow的渲染时机与mainWindow不同,canvas组件在topWindow中可能还未完全挂载到DOM树时就被访问
  2. uni.createCanvasContext方法在H5端依赖于DOM节点的实时查询,在topWindow中可能出现查询不到的情况

临时解决方案:

  1. 增加延迟时间,将setTimeout延迟到2000ms以上
  2. 使用条件渲染,确保canvas组件在topWindow完全渲染后再显示:
<canvas v-if="showCanvas" canvas-id="test_canvas" style="background-color: #ff0;width:100px;height:50px;"></canvas>
data() {
    return {
        showCanvas: false
    }
},
mounted() {
    setTimeout(() => {
        this.showCanvas = true;
        this.$nextTick(() => {
            let ctx = uni.createCanvasContext('test_canvas');
            // ...绘图代码
        });
    }, 500);
}
回到顶部