---
name: "canvas"
mode: "component"
versionRequirements:
  - { name: "基础库", version: "2.10.0" }
title: "canvas - 画布"
---

## canvas

> [VERSION] 基础库 >= 2.10.0

### 描述

画布组件，用于绘制图形。

### 属性

| 属性 | 类型 | 必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `type` | `string` | 否 | `"2d"` | canvas 类型 |
| `canvas-id` | `string` | 是 | `""` | canvas 组件的唯一标识符 |
| `disable-scroll` | `boolean` | 否 | `false` | 当在 canvas 中移动时，禁止屏幕滚动以及下拉刷新 |
| `auto-resize` | `boolean` | 否 | `false` | 是否开启画布大小自适应，画布宽高按 100% 适应 canvas 尺寸， 并会发送 resize 事件，此时可通过监听 bind:resize 事件，在回调中重新绘制画布 |

#### 事件

| 事件名 | 类型 | 描述 |
| --- | --- | --- |
| `resize` | `(event: CanvasResizeEvent) => void` | 画布大小变化时触发（需开启 auto-resize） |

**CanvasResizeEvent**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `type` | `"resize"` |  |
| `detail` | `CanvasResizeDetail` |  |

### 示例代码

#### 基础用法

*index.tyml*

```xml
<canvas canvas-id="myCanvas" type="2d" class="canvas" />
```

*index.tyss*

```css
.canvas {
  width: 300px;
  height: 300px;
  background-color: #f5f5f5;
}
```

*index.js*

```javascript
Page({
  onReady() {
    const ctx = ty.createCanvasContext('myCanvas');
    ctx.setFillStyle('#ff0000');
    ctx.fillRect(10, 10, 100, 100);
    ctx.setFillStyle('#4dabf7');
    ctx.fillRect(50, 50, 100, 100);
    ctx.draw();
  },
});
```

#### 触摸绘制

*index.tyml*

```xml
<canvas
  canvas-id="drawCanvas"
  type="2d"
  class="canvas"
  disable-scroll
  bind:touchstart="onTouchStart"
  bind:touchmove="onTouchMove"
  bind:touchend="onTouchEnd"
/>
```

*index.tyss*

```css
.canvas {
  width: 100%;
  height: 400px;
  border: 1px solid #eee;
}
```

*index.js*

```javascript
Page({
  data: { drawing: false },
  onReady() {
    this.ctx = ty.createCanvasContext('drawCanvas');
    this.ctx.setStrokeStyle('#1890ff');
    this.ctx.setLineWidth(3);
    this.ctx.setLineCap('round');
  },
  onTouchStart(e) {
    this.setData({ drawing: true });
    var touch = e.touches[0];
    this.ctx.beginPath();
    this.ctx.moveTo(touch.x, touch.y);
  },
  onTouchMove(e) {
    if (!this.data.drawing) return;
    var touch = e.touches[0];
    this.ctx.lineTo(touch.x, touch.y);
    this.ctx.stroke();
    this.ctx.draw(true);
    this.ctx.moveTo(touch.x, touch.y);
  },
  onTouchEnd() {
    this.setData({ drawing: false });
  },
});
```


<DemoBlock
  githubUrl="https://github.com/Tuya-Community/tuya-miniapp-demo/tree/master/canvas" qrCodeUrl="/images/qrCode/canvas.png"
  lang="zh">
</DemoBlock>

### 相关文档

- 使用 [rjs](/cn/miniapp/develop/miniapp/framework/api/render) 进行绘制, 可以获取到 canvas 节点, 可以绘制图表, 动画和各种图形等。

- 在逻辑层 js 中配合 [ty.createCanvasContext](/cn/miniapp/develop/miniapp/api/canvas/CanvasContext/createCanvasContext) API 使用, 此方法获取不到 canvas node 节点。
