小程序中canvas里draw()方法不执行
时间: 2024-03-21 07:39:14 浏览: 37
在小程序中,canvas 中的 draw 方法需要等到 canvas 元素渲染完毕后才能执行,因此如果在 canvas 元素没有渲染完毕时调用 draw 方法是不会执行的。为了解决这个问题,我们需要在 canvas 元素加载完毕后再调用 draw 方法。
以下是一个示例代码,展示了如何在 canvas 元素加载完毕后调用 draw 方法:
```html
<canvas id="myCanvas" style="width: 300px; height: 200px;"></canvas>
```
```javascript
Page({
onReady: function () {
const context = wx.createCanvasContext('myCanvas')
context.setFillStyle('red')
context.fillRect(0, 0, 100, 100)
context.draw(false, () => {
console.log('canvas draw success')
})
}
})
```
在上面的代码中,我们在 `onReady` 生命周期函数中创建了一个 canvas 上下文对象 `context`,然后使用 `context` 对象绘制了一个红色矩形,接着在 `context.draw` 方法的回调函数中打印了一条日志信息。
需要注意的是,由于小程序中的 canvas 组件是一个自定义组件,因此在调用 `wx.createCanvasContext` 方法时,需要传入 canvas 组件的 ID。在上面的代码中,我们将 canvas 组件的 ID 设置为 `myCanvas`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)