---
name: "Canvas"
mode: "api"
versionRequirements:
  - { name: "基础库", version: "2.21.8" }
title: "Canvas"
---

## Canvas

> [VERSION] 基础库 >= 2.21.8

> 💡 在 render-script（.rjs）里调用 this.instance.getCanvasById(canvasId) 获取，返回值是一个 Promise，
> resolve 得到 Canvas 实例（节点不存在时 resolve 为 null）。
> Canvas 实例支持 getContext、createImage、createImageData、createPath2D、requestAnimationFrame、cancelAnimationFrame 方法。

### 描述

Canvas 实例，在 render-script 中通过 this.instance.getCanvasById 获取

### 参数

无


### 返回值

类型: `Canvas`

Canvas 实例

#### 方法

| 方法名 | 说明 |
| --- | --- |
| `getContext` | 获取 Canvas 绘图上下文 |
| `createImage` | 创建一个图片对象，用于绘制到 Canvas 上 |
| `createImageData` | 创建一个 ImageData 对象，用于像素级操作 |
| `createPath2D` | 创建一个 Path2D 对象，用于声明路径 |
| `requestAnimationFrame` | 创建一个请求动画帧回调，在下次重绘之前调用指定的回调函数 |
| `cancelAnimationFrame` | 取消由 requestAnimationFrame 添加到计划中的动画帧请求 |

### 示例代码

#### 在 render-script 中获取 Canvas 实例

```rjs
// index.rjs
export default {
  mounted() {
    this.instance.getCanvasById('myCanvas').then((canvas) => {
      if (!canvas) return;
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = '#00AEEF';
      ctx.fillRect(20, 20, 120, 60);
    });
  },
};
```
