---
name: "CanvasContext"
mode: "api"
versionRequirements:
  - { name: "Base Library", version: "2.21.8" }
title: "CanvasContext"
---

## CanvasContext

> [VERSION] Base Library >= 2.21.8

> 💡 CanvasContext is the drawing context for the Mini Program canvas, used to draw on the canvas component.
> All drawing operations are rendered to the canvas only after calling draw().

### Description

CanvasContext instance, obtainable via ty.createCanvasContext

### Parameters

None


### Return Value

Type: `CanvasContext`

CanvasContext instance

#### Methods

| Method | Description |
| --- | --- |
| `draw` | Render the previously defined paths, transforms, and styles in the drawing context onto the canvas |
| `createLinearGradient` | Create a linear gradient |
| `createCircularGradient` | Create a circular gradient |
| `beginPath` | Begin a new path |
| `moveTo` | Move the path to a specified point on the canvas without creating a line |
| `lineTo` | Add a new point, then create a line from the last specified point to the target point |
| `arc` | Create an arc |
| `arcTo` | Draw an arc path based on control points and radius |
| `quadraticCurveTo` | Create a quadratic Bezier curve path |
| `bezierCurveTo` | Create a cubic Bezier curve path |
| `rect` | Create a rectangular path |
| `closePath` | Close a path, connecting the start and end points |
| `fill` | Fill the current path |
| `stroke` | Stroke the current path |
| `fillRect` | Fill a rectangle |
| `strokeRect` | Draw a rectangle (not filled) |
| `clearRect` | Clear the contents of the canvas within this rectangle |
| `fillText` | Draw filled text on the canvas |
| `strokeText` | Stroke text at the given (x, y) position |
| `scale` | After this call, the x and y coordinates of subsequently created paths will be scaled |
| `rotate` | Rotate the current coordinate system clockwise around the origin |
| `translate` | Translate the origin (0, 0) of the current coordinate system |
| `transform` | Multiply the current transform by a matrix |
| `setTransform` | Reset (overwrite) the current transform with a matrix |
| `save` | Save the drawing context |
| `restore` | Restore the previously saved drawing context |
| `setFillStyle` | Set fill color |
| `setStrokeStyle` | Set stroke color |
| `setGlobalAlpha` | Set global alpha |
| `setShadow` | Set shadow style |
| `setFontSize` | Set font size |
| `setLineCap` | Set line cap style |
| `setLineJoin` | Set line join style |
| `setLineWidth` | Set line width |
| `setMiterLimit` | Set miter limit |
| `setTextAlign` | Set text alignment |
| `setTextBaseline` | Set vertical text alignment |
| `setLineDash` | Set dash pattern |

### Examples

#### Basic usage

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