• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# CanvasRenderingContext2D
2
3Use **RenderingContext** to draw rectangles, text, images, and other objects on a canvas.
4
5> **NOTE**
6>
7> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8>
9> When you call drawing APIs in this module, the commands are stored in the associated **Canvas** component's command queue. These commands are only executed when the current frame enters the rendering phase and the associated **Canvas** component is visible. As such, avoid frequent drawing calls when the **Canvas** component is not visible to prevent command accumulation in the queue, which can lead to excessive memory usage.
10>
11> If the width or height of the **Canvas** component exceeds 8000 px, the CPU is used for rendering, which can significantly degrade performance.
12
13
14
15## APIs
16
17CanvasRenderingContext2D(settings?: RenderingContextSettings, unit?: LengthMetricsUnit)
18
19**Widget capability**: This API can be used in ArkTS widgets since API version 9.
20
21**Atomic service API**: This API can be used in atomic services since API version 11.
22
23**System capability**: SystemCapability.ArkUI.ArkUI.Full
24
25**Parameters**
26
27| Name     | Type | Mandatory  | Description   |
28| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
29| settings | [RenderingContextSettings](#renderingcontextsettings) | No   | Settings of the **CanvasRenderingContext2D** object. For details, see [RenderingContextSettings](#renderingcontextsettings).|
30| unit<sup>12+</sup>  | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No   | Unit mode of the **CanvasRenderingContext2D** object. The value cannot be dynamically changed once set. For details, see [LengthMetricsUnit](#lengthmetricsunit12).<br>Default value: **DEFAULT**|
31
32
33### RenderingContextSettings
34
35RenderingContextSettings(antialias?: boolean)
36
37Configures the settings of a **CanvasRenderingContext2D** object, including whether to enable antialiasing.
38
39**Widget capability**: This API can be used in ArkTS widgets since API version 9.
40
41**Atomic service API**: This API can be used in atomic services since API version 11.
42
43**System capability**: SystemCapability.ArkUI.ArkUI.Full
44
45**Parameters**
46
47| Name      | Type   | Mandatory  | Description                         |
48| --------- | ------- | ---- | ----------------------------- |
49| antialias | boolean | No   | Whether to enable antialiasing.<br>Default value: **false** |
50
51### LengthMetricsUnit<sup>12+</sup>
52
53Defines the unit of the **CanvasRenderingContext2D** object. The default unit is **LengthMetricsUnit.DEFAULT**, corresponding to the vp unit. The value cannot be dynamically changed once set. For details, see [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12).
54
55**Example**
56
57```ts
58// xxx.ets
59import { LengthMetricsUnit } from '@kit.ArkUI'
60
61@Entry
62@Component
63struct LengthMetricsUnitDemo {
64  private settings: RenderingContextSettings = new RenderingContextSettings(true);
65  private contextPX: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings, LengthMetricsUnit.PX);
66  private contextVP: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
67
68  build() {
69    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
70      Canvas(this.contextPX)
71        .width('100%')
72        .height(150)
73        .backgroundColor('#ffff00')
74        .onReady(() => {
75          this.contextPX.fillRect(10,10,100,100)
76          this.contextPX.clearRect(10,10,50,50)
77        })
78
79      Canvas(this.contextVP)
80        .width('100%')
81        .height(150)
82        .backgroundColor('#ffff00')
83        .onReady(() => {
84          this.contextVP.fillRect(10,10,100,100)
85          this.contextVP.clearRect(10,10,50,50)
86        })
87    }
88    .width('100%')
89    .height('100%')
90  }
91}
92```
93
94![CanvasContext2DUnitMode](figures/CanvasContext2DUnitMode.png)
95
96## Attributes
97
98**Widget capability**: This API can be used in ArkTS widgets since API version 9.
99
100**Atomic service API**: This API can be used in atomic services since API version 11.
101
102**System capability**: SystemCapability.ArkUI.ArkUI.Full
103
104| Name| Type| Read Only| Optional| Description|
105| --------- | ------------------------------- | ------------------ | ---------------------- | ---------------------------------------- |
106| [fillStyle](#fillstyle) | string \|number<sup>10+</sup> \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | No| No| Style used to fill an area.<br>- When the type is string, this attribute indicates the color of the fill area. For details about the color format, see the description for the string type in [ResourceColor](ts-types.md#resourcecolor).<br>Default value: **'#000000'**<br>- When the type is number, this attribute indicates the color of the fill area. Fully transparent colors are not supported. For details about the color format, see the description for the number type in [ResourceColor](ts-types.md#resourcecolor).<br>Default value: **0x000000**<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
107| [lineWidth](#linewidth) | number | No| No| Line width.<br>Default value: **1(px)**<br>Default unit: vp<br> The value cannot be **0** or a negative number. If it is set to **0** or a negative number, the default value is used instead.              |
108| [strokeStyle](#strokestyle)              | string \|number<sup>10+</sup> \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern)  | No| No| Stroke color.<br>- When the type is string, this attribute indicates the stroke color. For details about the color format, see the description for the string type in [ResourceColor](ts-types.md#resourcecolor).<br>Default value: **'#000000'**<br>- When the type is number, this attribute indicates the stroke color. Fully transparent colors are not supported. For details about the color format, see the description for the number type in [ResourceColor](ts-types.md#resourcecolor).<br>Default value: **0x000000**<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
109| [lineCap](#linecap)                      | [CanvasLineCap](#canvaslinecap) | No| No| Style of the line endpoints. The options are as follows:<br>- **'butt'**: The endpoints of the line are squared off.<br>- **'round'**: The endpoints of the line are rounded.<br>- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.<br>Default value: **'butt'**|
110| [lineJoin](#linejoin)                    | [CanvasLineJoin](#canvaslinejoin) | No| No| Style of the shape used to join line segments. The options are as follows:<br>- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.<br>- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.<br>- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>Default value: **'miter'**|
111| [miterLimit](#miterlimit)                | number | No| No| Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>Default value: **10** (px)<br>Unit: px<br>The value cannot be **0** or a negative number. If it is set to **0** or a negative number, the default value is used instead.|
112| [font](#font)                            | string | No| No| Font style.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.<br>- (Optional) **font-size**: font size and line height. The unit must be specified and can be px or vp.<br>- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**. Custom fonts are also supported, though they cannot be observed in DevEco Studio Previewer. For details, see the [custom font example](#font).<br>Default value: **'normal normal 14px sans-serif'**|
113| [textAlign](#textalign)                  | [CanvasTextAlign](#canvastextalign) | No| No| Text alignment mode. Available values are as follows:<br>- **'left'**: The text is left-aligned.<br>- **'right'**: The text is right-aligned.<br>- **'center'**: The text is center-aligned.<br>- **'start'**: The text is aligned with the start bound.<br>- **'end'**: The text is aligned with the end bound.<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>Default value: **'start'**|
114| [textBaseline](#textbaseline)            | [CanvasTextBaseline](#canvastextbaseline) | No| No| Horizontal alignment mode of text. Available values are as follows:<br>- **'alphabetic'**: The text baseline is the normal alphabetic baseline.<br>- **'top'**: The text baseline is on the top of the text bounding box.<br>- **'hanging'**: The text baseline is a hanging baseline over the text.<br>- **'middle'**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>Default value: **'alphabetic'**|
115| [globalAlpha](#globalalpha)              | number | No| No| Opacity. The value ranges from 0.0 (completely transparent) to 1.0 (completely opaque). If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.<br>Default value: **1.0**|
116| [lineDashOffset](#linedashoffset)        | number | No| No| Offset of the dashed line. The precision is float.<br>Default value: **0.0**<br>Default unit: vp|
117| [globalCompositeOperation](#globalcompositeoperation) | string | No| No| Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>Default value: **'source-over'**|
118| [shadowBlur](#shadowblur)                | number | No| No| Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float, and the value must be greater than or equal to 0.<br>Default value: **0.0**<br>Unit: px<br>The value cannot be a negative number. If it is set to a negative number, the default value is used instead.|
119| [shadowColor](#shadowcolor)              | string | No| No| Shadow color. For details about the color format, see the description for the string type in [ResourceColor](ts-types.md#resourcecolor).<br>Default value: transparent black|
120| [shadowOffsetX](#shadowoffsetx)          | number | No| No| X-axis shadow offset relative to the original object.<br>Default value: **0.0**<br>Default unit: vp|
121| [shadowOffsetY](#shadowoffsety)          | number | No| No| Y-axis shadow offset relative to the original object.<br>Default value: **0.0**<br>Default unit: vp|
122| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | No| No| Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>Default value: **true**|
123| [height](#height)                        | number | Yes| No| Component height.<br>Default unit: vp|
124| [width](#width)                          | number | Yes| No| Component width.<br>Default unit: vp|
125| [imageSmoothingQuality](#imagesmoothingquality) | [ImageSmoothingQuality](#imagesmoothingquality) | No| No| Quality of image smoothing. This attribute works only when **imageSmoothingEnabled** is set to **true**.<br>Default value: **'low'**|
126| [direction](#direction)                  | [CanvasDirection](#canvasdirection) | No| No| Text direction used for drawing text.<br>Default value: **'inherit'**|
127|  [filter](#filter)                        | string | No| No| Filter effect for an image. You can combine any number of filter effects.<br>Available values are as follows:<br>- **'none'**: no filter effect.<br>- 'blur(\<length>)': applies the Gaussian blur for the image. The value must be greater than or equal to 0. The unit can be px, vp, or rem. The default unit is vp, and the default value is **blur(0px)**.<br>- 'brightness([\<number>\|\<percentage>])': applies a linear multiplication to the image to make it look brighter or darker. The value can be a number or percentage. It must be greater than or equal to 0. The default value is **brightness(1)**.<br>- 'contrast([\<number>\|\<percentage>])': adjusts the image contrast. The value can be a number or percentage. It must be greater than or equal to 0. The default value is **contrast(1)**.<br>- 'grayscale([\<number>\|\<percentage>])': converts the image to a grayscale image. The value can be a number or percentage. The value range is [0, 1]. The default value is **grayscale(0)**.<br>- 'hue-rotate(\<angle>)': applies hue rotation to the image. The value ranges from 0deg to 360deg. The default value is **hue-rotate (0deg)**.<br>- 'invert([\<number>\|\<percentage>])': inverts the input image. The value can be a number or percentage. The value range is [0, 1]. The default value is **invert (0)**.<br>- 'opacity([\<number>\|\<percentage>])': sets the opacity of the image. The value can be a number or percentage. The value range is [0, 1]. The default value is **opacity(1)**.<br>- 'saturate([\<number>\|\<percentage>])': sets the saturation of the image. The value can be a number or percentage. It must be greater than or equal to 0. The default value is **saturate(1)**.<br>- 'sepia([\<number>\|\<percentage>])': converts the image to dark brown. The value can be a number or percentage. The value range is [0, 1]. The default value is **sepia(0)**.|
128| [canvas<sup>13+</sup>](#canvas13)                        | [FrameNode](../../apis-arkui/js-apis-arkui-frameNode.md) | Yes| No| FrameNode instance of the **Canvas** component associated with **CanvasRenderingContext2D**.<br>It can be used to listen for the visibility status of the associated **Canvas** component.<br>Default value: **null**|
129| [letterSpacing<sup>18+</sup>](#letterspacing18)                  | string \| [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No| No| Spacing between characters.<br>When the LengthMetrics type is used:<br>The spacing is set according to the specified unit.<br>The FP, PERCENT, and LPX units are not supported and will be treated as invalid values.<br>Negative and fractional values are supported. When set to a fraction, the spacing is not rounded.<br>When the string type is used:<br>Percentage values are not supported and will be treated as invalid.<br>Negative and fractional values are supported. When set to a fraction, the spacing is not rounded.<br>If no unit is specified (for example, **letterSpacing = '10'**) and **LengthMetricsUnit** is not set, the default unit is vp.<br>If **LengthMetricsUnit** is set to px, the default unit is px.<br>If a unit is specified (for example, **letterSpacing='10vp'**), the spacing is set according to the specified unit.<br>Default value: **0** (Invalid values are treated as the default value.)<br>**NOTE**<br>The LengthMetrics type is recommended for better performance.|
130
131> **NOTE**
132>
133> The string-type value of **fillStyle**, **shadowColor**, and **strokeStyle** can be in 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', or '\#FFFFFF' format.
134
135
136### fillStyle
137
138```ts
139// xxx.ets
140@Entry
141@Component
142struct FillStyleExample {
143  private settings: RenderingContextSettings = new RenderingContextSettings(true)
144  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
145
146  build() {
147    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
148      Canvas(this.context)
149        .width('100%')
150        .height('100%')
151        .backgroundColor('#ffff00')
152        .onReady(() =>{
153          this.context.fillStyle = '#0000ff'
154          this.context.fillRect(20, 20, 150, 100)
155        })
156    }
157    .width('100%')
158    .height('100%')
159  }
160}
161```
162
163![en-us_image_0000001257058395](figures/en-us_image_0000001257058395.png)
164
165
166### lineWidth
167
168```ts
169// xxx.ets
170@Entry
171@Component
172struct LineWidthExample {
173  private settings: RenderingContextSettings = new RenderingContextSettings(true)
174  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
175
176  build() {
177    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
178      Canvas(this.context)
179        .width('100%')
180        .height('100%')
181        .backgroundColor('#ffff00')
182        .onReady(() =>{
183        this.context.lineWidth = 5
184        this.context.strokeRect(25, 25, 85, 105)
185      })
186    }
187    .width('100%')
188    .height('100%')
189  }
190}
191```
192
193![en-us_image_0000001212378408](figures/en-us_image_0000001212378408.png)
194
195
196### strokeStyle
197
198```ts
199// xxx.ets
200@Entry
201@Component
202struct StrokeStyleExample {
203  private settings: RenderingContextSettings = new RenderingContextSettings(true)
204  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
205
206  build() {
207    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
208      Canvas(this.context)
209        .width('100%')
210        .height('100%')
211        .backgroundColor('#ffff00')
212        .onReady(() =>{
213          this.context.lineWidth = 10
214          this.context.strokeStyle = '#0000ff'
215          this.context.strokeRect(25, 25, 155, 105)
216        })
217    }
218    .width('100%')
219    .height('100%')
220  }
221}
222```
223
224
225![en-us_image_0000001212218446](figures/en-us_image_0000001212218446.png)
226
227
228### lineCap
229
230```ts
231// xxx.ets
232@Entry
233@Component
234struct LineCapExample {
235  private settings: RenderingContextSettings = new RenderingContextSettings(true)
236  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
237
238  build() {
239    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
240      Canvas(this.context)
241        .width('100%')
242        .height('100%')
243        .backgroundColor('#ffff00')
244        .onReady(() =>{
245          this.context.lineWidth = 8
246          this.context.beginPath()
247          this.context.lineCap = 'round'
248          this.context.moveTo(30, 50)
249          this.context.lineTo(220, 50)
250          this.context.stroke()
251        })
252    }
253    .width('100%')
254    .height('100%')
255  }
256}
257```
258
259![en-us_image_0000001212378406](figures/en-us_image_0000001212378406.png)
260
261
262### lineJoin
263
264```ts
265// xxx.ets
266@Entry
267@Component
268struct LineJoinExample {
269  private settings: RenderingContextSettings = new RenderingContextSettings(true)
270  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
271
272  build() {
273    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
274      Canvas(this.context)
275        .width('100%')
276        .height('100%')
277        .backgroundColor('#ffff00')
278        .onReady(() =>{
279        this.context.beginPath()
280        this.context.lineWidth = 8
281        this.context.lineJoin = 'miter'
282        this.context.moveTo(30, 30)
283        this.context.lineTo(120, 60)
284        this.context.lineTo(30, 110)
285        this.context.stroke()
286      })
287    }
288    .width('100%')
289    .height('100%')
290  }
291}
292```
293
294![en-us_image_0000001212218438](figures/en-us_image_0000001212218438.png)
295
296
297### miterLimit
298
299```ts
300// xxx.ets
301@Entry
302@Component
303struct MiterLimit {
304  private settings: RenderingContextSettings = new RenderingContextSettings(true)
305  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
306
307  build() {
308    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
309      Canvas(this.context)
310        .width('100%')
311        .height('100%')
312        .backgroundColor('#ffff00')
313        .onReady(() =>{
314          this.context.lineWidth = 8
315          this.context.lineJoin = 'miter'
316          this.context.miterLimit = 3
317          this.context.moveTo(30, 30)
318          this.context.lineTo(60, 35)
319          this.context.lineTo(30, 37)
320          this.context.stroke()
321      })
322    }
323    .width('100%')
324    .height('100%')
325  }
326}
327```
328
329![en-us_image_0000001212378398](figures/en-us_image_0000001212378398.png)
330
331
332### font
333
334Before using the **font** property to load custom fonts, you must first register the custom font in the **EntryAbility.ets** file located in the **src/main/ets/entryability/** directory. The following is an example of how to do this.
335
336> The value of **familyName** must be a continuous string without spaces, for example, **"customFont"**. Otherwise, the **font** property will fail to load the custom font.
337>
338> The **familySrc** path should point to the font file located in the **font** folder, which is at the same level as the **pages** folder.
339
340```ts
341onWindowStageCreate(windowStage: window.WindowStage): void {
342  windowStage.loadContent('pages/Index', (err) => {
343    windowStage.getMainWindow().then(res => {
344      const uiCtc = res.getUIContext()
345      uiCtc.getFont().registerFont({
346        familyName: 'customFont',
347        familySrc: '/font/myFont.ttf'
348      })
349    })
350  });
351}
352```
353
354```ts
355// xxx.ets
356@Entry
357@Component
358struct Fonts {
359  private settings: RenderingContextSettings = new RenderingContextSettings(true)
360  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
361
362  build() {
363    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
364      Canvas(this.context)
365        .width('100%')
366        .height('100%')
367        .backgroundColor('rgb(213,213,213)')
368        .onReady(() =>{
369          this.context.font = '30px sans-serif'
370          this.context.fillText("Hello px", 20, 60)
371          this.context.font = '30vp sans-serif'
372          this.context.fillText("Hello vp", 20, 100)
373          // Use a custom font by specifying its familyName.
374          this.context.font = '30vp customFont'
375          this.context.fillText("Hello", 20, 140)
376        })
377    }
378    .width('100%')
379    .height('100%')
380  }
381}
382```
383
384![new_font](figures/new_font.jpeg)
385
386### textAlign
387
388```ts
389// xxx.ets
390@Entry
391@Component
392struct CanvasExample {
393  private settings: RenderingContextSettings = new RenderingContextSettings(true)
394  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
395
396  build() {
397    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
398      Canvas(this.context)
399        .width('100%')
400        .height('100%')
401        .backgroundColor('#ffff00')
402        .onReady(() => {
403          this.context.strokeStyle = '#0000ff'
404          this.context.moveTo(140, 10)
405          this.context.lineTo(140, 160)
406          this.context.stroke()
407          this.context.font = '18px sans-serif'
408          this.context.textAlign = 'start'
409          this.context.fillText('textAlign=start', 140, 60)
410          this.context.textAlign = 'end'
411          this.context.fillText('textAlign=end', 140, 80)
412          this.context.textAlign = 'left'
413          this.context.fillText('textAlign=left', 140, 100)
414          this.context.textAlign = 'center'
415          this.context.fillText('textAlign=center', 140, 120)
416          this.context.textAlign = 'right'
417          this.context.fillText('textAlign=right', 140, 140)
418        })
419    }
420    .width('100%')
421    .height('100%')
422  }
423}
424```
425
426![en-us_image_0000001256978351](figures/en-us_image_0000001256978351.png)
427
428
429### textBaseline
430
431```ts
432// xxx.ets
433@Entry
434@Component
435struct TextBaseline {
436  private settings: RenderingContextSettings = new RenderingContextSettings(true)
437  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
438
439  build() {
440    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
441      Canvas(this.context)
442        .width('100%')
443        .height('100%')
444        .backgroundColor('rgb(213,213,213)')
445        .onReady(() => {
446          this.context.strokeStyle = 'rgb(213,213,213)'
447          this.context.moveTo(0, 120)
448          this.context.lineTo(400, 120)
449          this.context.stroke()
450          this.context.font = '20px sans-serif'
451          this.context.textBaseline = 'top'
452          this.context.fillText('Top', 10, 120)
453          this.context.textBaseline = 'bottom'
454          this.context.fillText('Bottom', 55, 120)
455          this.context.textBaseline = 'middle'
456          this.context.fillText('Middle', 125, 120)
457          this.context.textBaseline = 'alphabetic'
458          this.context.fillText('Alphabetic', 195, 120)
459          this.context.textBaseline = 'hanging'
460          this.context.fillText('Hanging', 295, 120)
461      })
462    }
463    .width('100%')
464    .height('100%')
465  }
466}
467```
468
469![textBaseline](figures/textBaseline.jpg)
470
471
472### globalAlpha
473
474```ts
475// xxx.ets
476@Entry
477@Component
478struct GlobalAlpha {
479  private settings: RenderingContextSettings = new RenderingContextSettings(true)
480  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
481
482  build() {
483    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
484      Canvas(this.context)
485        .width('100%')
486        .height('100%')
487        .backgroundColor('#ffff00')
488        .onReady(() =>{
489          this.context.fillStyle = 'rgb(0,0,255)'
490          this.context.fillRect(0, 0, 50, 50)
491          this.context.globalAlpha = 0.4
492          this.context.fillStyle = 'rgb(0,0,255)'
493          this.context.fillRect(50, 50, 50, 50)
494      })
495    }
496    .width('100%')
497    .height('100%')
498  }
499}
500```
501
502![en-us_image_0000001194192434](figures/en-us_image_0000001194192434.png)
503
504
505### lineDashOffset
506
507```ts
508// xxx.ets
509@Entry
510@Component
511struct LineDashOffset {
512  private settings: RenderingContextSettings = new RenderingContextSettings(true)
513  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
514
515  build() {
516    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
517      Canvas(this.context)
518        .width('100%')
519        .height('100%')
520        .backgroundColor('#ffff00')
521        .onReady(() =>{
522          this.context.arc(100, 75, 50, 0, 6.28)
523          this.context.setLineDash([10,20])
524          this.context.lineDashOffset = 10.0
525          this.context.stroke()
526      })
527    }
528    .width('100%')
529    .height('100%')
530  }
531}
532```
533
534![en-us_image_0000001194352434](figures/en-us_image_0000001194352434.png)
535
536
537### globalCompositeOperation
538
539| Name              | Description                      |
540| ---------------- | ------------------------ |
541| source-over      | Displays the new drawing above the existing drawing. Default value.  |
542| source-atop      | Displays the new drawing on the top of the existing drawing.       |
543| source-in        | Displays the new drawing inside the existing drawing.        |
544| source-out       | Displays part of the new drawing that is outside of the existing drawing.       |
545| destination-over | Displays the existing drawing above the new drawing.       |
546| destination-atop | Displays the existing drawing on the top of the new drawing.       |
547| destination-in   | Displays the existing drawing inside the new drawing.        |
548| destination-out  | Displays the existing drawing outside the new drawing.        |
549| lighter          | Displays both the new and existing drawing.         |
550| copy             | Displays the new drawing and neglects the existing drawing.       |
551| xor              | Combines the new drawing and existing drawing using the XOR operation.|
552
553```ts
554// xxx.ets
555@Entry
556@Component
557struct GlobalCompositeOperation {
558  private settings: RenderingContextSettings = new RenderingContextSettings(true)
559  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
560
561  build() {
562    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
563      Canvas(this.context)
564        .width('100%')
565        .height('100%')
566        .backgroundColor('#ffff00')
567        .onReady(() =>{
568          this.context.fillStyle = 'rgb(255,0,0)'
569          this.context.fillRect(20, 20, 50, 50)
570          this.context.globalCompositeOperation = 'source-over'
571          this.context.fillStyle = 'rgb(0,0,255)'
572          this.context.fillRect(50, 50, 50, 50)
573          this.context.fillStyle = 'rgb(255,0,0)'
574          this.context.fillRect(120, 20, 50, 50)
575          this.context.globalCompositeOperation = 'destination-over'
576          this.context.fillStyle = 'rgb(0,0,255)'
577          this.context.fillRect(150, 50, 50, 50)
578      })
579    }
580    .width('100%')
581    .height('100%')
582  }
583}
584```
585
586![en-us_image_0000001211898480](figures/en-us_image_0000001211898480.png)
587
588
589### shadowBlur
590
591```ts
592// xxx.ets
593@Entry
594@Component
595struct ShadowBlur {
596  private settings: RenderingContextSettings = new RenderingContextSettings(true)
597  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
598
599  build() {
600    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
601      Canvas(this.context)
602        .width('100%')
603        .height('100%')
604        .backgroundColor('#ffff00')
605        .onReady(() =>{
606          this.context.shadowBlur = 30
607          this.context.shadowColor = 'rgb(0,0,0)'
608          this.context.fillStyle = 'rgb(255,0,0)'
609          this.context.fillRect(20, 20, 100, 80)
610      })
611    }
612    .width('100%')
613    .height('100%')
614  }
615}
616```
617
618![en-us_image_0000001256978343](figures/en-us_image_0000001256978343.png)
619
620
621### shadowColor
622
623```ts
624// xxx.ets
625@Entry
626@Component
627struct ShadowColor {
628  private settings: RenderingContextSettings = new RenderingContextSettings(true)
629  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
630
631  build() {
632    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
633      Canvas(this.context)
634        .width('100%')
635        .height('100%')
636        .backgroundColor('#ffff00')
637        .onReady(() =>{
638          this.context.shadowBlur = 30
639          this.context.shadowColor = 'rgb(0,0,255)'
640          this.context.fillStyle = 'rgb(255,0,0)'
641          this.context.fillRect(30, 30, 100, 100)
642      })
643    }
644    .width('100%')
645    .height('100%')
646  }
647}
648```
649
650![en-us_image_0000001257138353](figures/en-us_image_0000001257138353.png)
651
652
653### shadowOffsetX
654
655```ts
656// xxx.ets
657@Entry
658@Component
659struct ShadowOffsetX {
660  private settings: RenderingContextSettings = new RenderingContextSettings(true)
661  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
662
663  build() {
664    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
665      Canvas(this.context)
666        .width('100%')
667        .height('100%')
668        .backgroundColor('#ffff00')
669        .onReady(() =>{
670          this.context.shadowBlur = 10
671          this.context.shadowOffsetX = 20
672          this.context.shadowColor = 'rgb(0,0,0)'
673          this.context.fillStyle = 'rgb(255,0,0)'
674          this.context.fillRect(20, 20, 100, 80)
675      })
676    }
677    .width('100%')
678    .height('100%')
679  }
680}
681```
682
683![en-us_image_0000001212218436](figures/en-us_image_0000001212218436.png)
684
685
686### shadowOffsetY
687
688```ts
689// xxx.ets
690@Entry
691@Component
692struct ShadowOffsetY {
693  private settings: RenderingContextSettings = new RenderingContextSettings(true)
694  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
695  build() {
696    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
697      Canvas(this.context)
698        .width('100%')
699        .height('100%')
700        .backgroundColor('#ffff00')
701        .onReady(() =>{
702          this.context.shadowBlur = 10
703          this.context.shadowOffsetY = 20
704          this.context.shadowColor = 'rgb(0,0,0)'
705          this.context.fillStyle = 'rgb(255,0,0)'
706          this.context.fillRect(30, 30, 100, 100)
707      })
708    }
709    .width('100%')
710    .height('100%')
711  }
712}
713```
714
715![en-us_image_0000001212378410](figures/en-us_image_0000001212378410.png)
716
717
718### imageSmoothingEnabled
719
720```ts
721// xxx.ets
722@Entry
723@Component
724struct ImageSmoothingEnabled {
725  private settings: RenderingContextSettings = new RenderingContextSettings(true)
726  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
727  private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
728
729  build() {
730    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
731      Canvas(this.context)
732        .width('100%')
733        .height('100%')
734        .backgroundColor('#ffff00')
735        .onReady(() =>{
736          this.context.imageSmoothingEnabled = false
737          this.context.drawImage( this.img,0,0,400,200)
738      })
739    }
740    .width('100%')
741    .height('100%')
742  }
743}
744```
745
746![en-us_image_0000001211898472](figures/en-us_image_0000001211898472.png)
747
748
749### height
750
751```ts
752// xxx.ets
753@Entry
754@Component
755struct HeightExample {
756  private settings: RenderingContextSettings = new RenderingContextSettings(true)
757  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
758
759  build() {
760    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
761      Canvas(this.context)
762        .width(300)
763        .height(300)
764        .backgroundColor('#ffff00')
765        .onReady(() => {
766          let h = this.context.height
767          this.context.fillRect(0, 0, 300, h/2)
768        })
769    }
770    .width('100%')
771    .height('100%')
772  }
773}
774```
775
776![en-us_image_canvas_height](figures/en-us_image_canvas_height.png)
777
778
779### width
780
781```ts
782// xxx.ets
783@Entry
784@Component
785struct WidthExample {
786  private settings: RenderingContextSettings = new RenderingContextSettings(true)
787  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
788
789  build() {
790    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
791      Canvas(this.context)
792        .width(300)
793        .height(300)
794        .backgroundColor('#ffff00')
795        .onReady(() => {
796          let w = this.context.width
797          this.context.fillRect(0, 0, w/2, 300)
798        })
799    }
800    .width('100%')
801    .height('100%')
802  }
803}
804```
805
806![en-us_image_canvas_width](figures/en-us_image_canvas_width.png)
807
808
809### canvas<sup>13+</sup>
810
811```ts
812import { FrameNode } from '@kit.ArkUI'
813// xxx.ets
814@Entry
815@Component
816struct CanvasExample {
817  private settings: RenderingContextSettings = new RenderingContextSettings(true)
818  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
819  private text: string = ''
820
821  build() {
822    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
823      Canvas(this.context)
824        .width('100%')
825        .height('100%')
826        .backgroundColor('#ffff00')
827        .onReady(() => {
828          let node: FrameNode = this.context.canvas
829          node?.commonEvent.setOnVisibleAreaApproximateChange(
830            { ratios: [0, 1], expectedUpdateInterval: 10},
831            (isVisible: boolean, currentRatio: number) => {
832              if (!isVisible && currentRatio <= 0.0) {
833                this.text = 'Canvas is completely invisible.'
834              }
835              if (isVisible && currentRatio >= 1.0) {
836                this.text = 'Canvas is fully visible.'
837              }
838              this.context.reset()
839              this.context.font = '30vp sans-serif'
840              this.context.fillText(this.text, 50, 50)
841            }
842          )
843        })
844    }
845    .width('100%')
846    .height('100%')
847  }
848}
849```
850
851![en-us_image_canvas](figures/en-us_image_canvas.png)
852
853
854### imageSmoothingQuality
855
856```ts
857  // xxx.ets
858  @Entry
859  @Component
860  struct ImageSmoothingQualityDemo {
861    private settings: RenderingContextSettings = new RenderingContextSettings(true);
862    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
863    private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");
864
865    build() {
866      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
867        Canvas(this.context)
868          .width('100%')
869          .height('100%')
870          .backgroundColor('#ffff00')
871          .onReady(() =>{
872            let ctx = this.context
873            ctx.imageSmoothingEnabled = true
874            ctx.imageSmoothingQuality = 'high'
875            ctx.drawImage(this.img, 0, 0, 400, 200)
876          })
877      }
878      .width('100%')
879      .height('100%')
880    }
881  }
882```
883
884![ImageSmoothingQualityDemo](figures/ImageSmoothingQualityDemo.jpeg)
885
886
887### direction
888
889```ts
890  // xxx.ets
891  @Entry
892  @Component
893  struct DirectionDemo {
894    private settings: RenderingContextSettings = new RenderingContextSettings(true);
895    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
896
897    build() {
898      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
899        Canvas(this.context)
900          .width('100%')
901          .height('100%')
902          .backgroundColor('#ffff00')
903          .onReady(() =>{
904            let ctx = this.context
905            ctx.font = '48px serif';
906            ctx.textAlign = 'start'
907            ctx.fillText("Hi ltr!", 200, 50);
908
909            ctx.direction = "rtl";
910            ctx.fillText("Hi rtl!", 200, 100);
911          })
912      }
913      .width('100%')
914      .height('100%')
915    }
916  }
917```
918
919![directionDemo](figures/directionDemo.jpeg)
920
921
922### filter
923
924```ts
925  // xxx.ets
926  @Entry
927  @Component
928  struct FilterDemo {
929    private settings: RenderingContextSettings = new RenderingContextSettings(true);
930    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
931    private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
932
933    build() {
934      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
935        Canvas(this.context)
936          .width('100%')
937          .height('100%')
938          .onReady(() => {
939            let ctx = this.context
940            let img = this.img
941
942            ctx.drawImage(img, 0, 0, 100, 100);
943
944            ctx.filter = 'grayscale(50%)';
945            ctx.drawImage(img, 100, 0, 100, 100);
946
947            ctx.filter = 'sepia(60%)';
948            ctx.drawImage(img, 200, 0, 100, 100);
949
950            ctx.filter = 'saturate(30%)';
951            ctx.drawImage(img, 0, 100, 100, 100);
952
953            ctx.filter = 'hue-rotate(90deg)';
954            ctx.drawImage(img, 100, 100, 100, 100);
955
956            ctx.filter = 'invert(100%)';
957            ctx.drawImage(img, 200, 100, 100, 100);
958
959            ctx.filter = 'opacity(25%)';
960            ctx.drawImage(img, 0, 200, 100, 100);
961
962            ctx.filter = 'brightness(0.4)';
963            ctx.drawImage(img, 100, 200, 100, 100);
964
965            ctx.filter = 'contrast(200%)';
966            ctx.drawImage(img, 200, 200, 100, 100);
967
968            ctx.filter = 'blur(5px)';
969            ctx.drawImage(img, 0, 300, 100, 100);
970
971            // Applying multiple filters
972            ctx.filter = 'opacity(50%) contrast(200%) grayscale(50%)';
973            ctx.drawImage(img, 100, 300, 100, 100);
974          })
975      }
976      .width('100%')
977      .height('100%')
978    }
979  }
980```
981
982![filterDemo](figures/filterDemo.jpeg)
983
984### letterSpacing<sup>18+</sup>
985
986```ts
987  // xxx.ets
988  import { LengthMetrics, LengthUnit } from '@kit.ArkUI'
989
990  @Entry
991  @Component
992  struct letterSpacingDemo {
993    private settings: RenderingContextSettings = new RenderingContextSettings(true)
994    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
995
996    build() {
997      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
998        Canvas(this.context)
999          .width('100%')
1000          .height('100%')
1001          .backgroundColor('rgb(213,213,213)')
1002          .onReady(() => {
1003            this.context.font = '30vp'
1004            this.context.letterSpacing = '10vp'
1005            this.context.fillText('hello world', 30, 50)
1006            this.context.letterSpacing = new LengthMetrics(10, LengthUnit.VP)
1007            this.context.fillText('hello world', 30, 100)
1008          })
1009      }
1010      .width('100%')
1011      .height('100%')
1012    }
1013  }
1014```
1015
1016![letterSpacingDemo](figures/letterSpacingDemo.jpeg)
1017
1018## Methods
1019
1020Calls to the following methods on hidden pages will result in cache data. Therefore, avoid frequently refreshing the canvas on hidden pages.
1021
1022### fillRect
1023
1024fillRect(x: number, y: number, w: number, h: number): void
1025
1026Fills a rectangle on the canvas.
1027
1028**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1029
1030**Atomic service API**: This API can be used in atomic services since API version 11.
1031
1032**System capability**: SystemCapability.ArkUI.ArkUI.Full
1033
1034**Parameters**
1035
1036| Name    | Type    | Mandatory| Description           |
1037| ------ | ------ | ---- | ------------- |
1038| x      | number | Yes | X coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
1039| y      | number | Yes | Y coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
1040| w      | number | Yes | Width of the rectangle.<br>Default unit: vp|
1041| h      | number | Yes | Height of the rectangle.<br>Default unit: vp|
1042
1043**Example**
1044
1045  ```ts
1046  // xxx.ets
1047  @Entry
1048  @Component
1049  struct FillRect {
1050    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1051    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1052
1053    build() {
1054      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1055        Canvas(this.context)
1056          .width('100%')
1057          .height('100%')
1058          .backgroundColor('rgb(213,213,213)')
1059          .onReady(() => {
1060            this.context.fillRect(30, 30, 100, 100)
1061         })
1062        }
1063      .width('100%')
1064      .height('100%')
1065    }
1066  }
1067  ```
1068
1069  ![fillRect](figures/fillRect.jpg)
1070
1071
1072### strokeRect
1073
1074strokeRect(x: number, y: number, w: number, h: number): void
1075
1076Draws an outlined rectangle on the canvas.
1077
1078**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1079
1080**Atomic service API**: This API can be used in atomic services since API version 11.
1081
1082**System capability**: SystemCapability.ArkUI.ArkUI.Full
1083
1084**Parameters**
1085
1086| Name  | Type    | Mandatory  | Description          |
1087| ---- | ------ | ----  | ------------ |
1088| x    | number | Yes    | X coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
1089| y    | number | Yes    | Y coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
1090| w    | number | Yes    | Width of the rectangle.<br>Default unit: vp|
1091| h    | number | Yes    | Height of the rectangle.<br>Default unit: vp|
1092
1093**Example**
1094
1095  ```ts
1096  // xxx.ets
1097  @Entry
1098  @Component
1099  struct StrokeRect {
1100    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1101    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1102
1103    build() {
1104      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1105        Canvas(this.context)
1106          .width('100%')
1107          .height('100%')
1108          .backgroundColor('#ffff00')
1109          .onReady(() =>{
1110            this.context.strokeRect(30, 30, 200, 150)
1111        })
1112      }
1113      .width('100%')
1114      .height('100%')
1115    }
1116  }
1117  ```
1118
1119  ![en-us_image_0000001194352436](figures/en-us_image_0000001194352436.png)
1120
1121
1122### clearRect
1123
1124clearRect(x: number, y: number, w: number, h: number): void
1125
1126Clears the content in a rectangle on the canvas.
1127
1128**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1129
1130**Atomic service API**: This API can be used in atomic services since API version 11.
1131
1132**System capability**: SystemCapability.ArkUI.ArkUI.Full
1133
1134**Parameters**
1135
1136| Name  | Type    | Mandatory | Description |
1137| ---- | ------ | ---- | ------------- |
1138| x    | number | Yes| X coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
1139| y    | number | Yes| Y coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
1140| w    | number | Yes| Width of the rectangle.<br>Default unit: vp|
1141| h    | number | Yes| Height of the rectangle.<br>Default unit: vp|
1142
1143**Example**
1144
1145  ```ts
1146  // xxx.ets
1147  @Entry
1148  @Component
1149  struct ClearRect {
1150    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1151    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1152
1153    build() {
1154      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1155        Canvas(this.context)
1156          .width('100%')
1157          .height('100%')
1158          .backgroundColor('#ffff00')
1159          .onReady(() =>{
1160            this.context.fillStyle = 'rgb(0,0,255)'
1161            this.context.fillRect(20,20,200,200)
1162            this.context.clearRect(30,30,150,100)
1163        })
1164      }
1165      .width('100%')
1166      .height('100%')
1167    }
1168  }
1169  ```
1170
1171  ![en-us_image_0000001238952377](figures/en-us_image_0000001238952377.png)
1172
1173
1174### fillText
1175
1176fillText(text: string, x: number, y: number, maxWidth?: number): void
1177
1178Draws filled text on the canvas.
1179
1180**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1181
1182**Atomic service API**: This API can be used in atomic services since API version 11.
1183
1184**System capability**: SystemCapability.ArkUI.ArkUI.Full
1185
1186**Parameters**
1187
1188| Name      | Type    | Mandatory  | Description|
1189| -------- | ------ | ---- | --------------- |
1190| text     | string | Yes   | Text to draw.|
1191| x        | number | Yes   | X coordinate of the lower left corner of the text.<br>Default unit: vp|
1192| y        | number | Yes   | Y coordinate of the lower left corner of the text.<br>Default unit: vp|
1193| maxWidth | number | No   | Maximum width allowed for the text.<br>Default unit: vp<br>Default value: no width restriction|
1194
1195**Example**
1196
1197  ```ts
1198  // xxx.ets
1199  @Entry
1200  @Component
1201  struct FillText {
1202    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1203    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1204
1205    build() {
1206      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1207        Canvas(this.context)
1208          .width('100%')
1209          .height('100%')
1210          .backgroundColor('#ffff00')
1211          .onReady(() =>{
1212            this.context.font = '30px sans-serif'
1213            this.context.fillText("Hello World!", 20, 100)
1214        })
1215      }
1216      .width('100%')
1217      .height('100%')
1218    }
1219  }
1220  ```
1221
1222  ![en-us_image_0000001194032458](figures/en-us_image_0000001194032458.png)
1223
1224
1225### strokeText
1226
1227strokeText(text: string, x: number, y: number, maxWidth?: number): void
1228
1229Draws a text stroke on the canvas.
1230
1231**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1232
1233**Atomic service API**: This API can be used in atomic services since API version 11.
1234
1235**System capability**: SystemCapability.ArkUI.ArkUI.Full
1236
1237**Parameters**
1238
1239| Name      | Type    | Mandatory| Description    |
1240| -------- | ------ | ---- | --------------- |
1241| text     | string | Yes   | Text to draw.|
1242| x        | number | Yes   | X coordinate of the lower left corner of the text.<br>Default unit: vp|
1243| y        | number | Yes   | Y coordinate of the lower left corner of the text.<br>Default unit: vp|
1244| maxWidth | number | No   | Maximum width of the text.<br>Default unit: vp<br>Default value: no width restriction|
1245
1246**Example**
1247
1248  ```ts
1249  // xxx.ets
1250  @Entry
1251  @Component
1252  struct StrokeText {
1253    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1254    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1255
1256    build() {
1257      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1258        Canvas(this.context)
1259          .width('100%')
1260          .height('100%')
1261          .backgroundColor('rgb(213,213,213)')
1262          .onReady(() => {
1263            this.context.font = '50vp sans-serif'
1264            this.context.strokeText("Hello World!", 20, 60)
1265        })
1266      }
1267      .width('100%')
1268      .height('100%')
1269    }
1270  }
1271  ```
1272
1273  ![strokeText](figures/strokeText.jpg)
1274
1275
1276### measureText
1277
1278measureText(text: string): TextMetrics
1279
1280Measures the specified text to obtain its width. This API returns a **TextMetrics** object. Note that the width obtained may vary by device.
1281
1282**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1283
1284**Atomic service API**: This API can be used in atomic services since API version 11.
1285
1286**System capability**: SystemCapability.ArkUI.ArkUI.Full
1287
1288**Parameters**
1289
1290| Name  | Type    | Mandatory  | Description        |
1291| ---- | ------ | ---- |---------- |
1292| text | string | Yes | Text to be measured.|
1293
1294**Return value**
1295
1296| Type         | Description                                      |
1297| ----------- | ---------------------------------------- |
1298| [TextMetrics](#textmetrics) | **TextMetrics** object.|
1299
1300**Example**
1301
1302  ```ts
1303  // xxx.ets
1304  @Entry
1305  @Component
1306  struct MeasureText {
1307    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1308    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1309
1310    build() {
1311      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1312        Canvas(this.context)
1313          .width('100%')
1314          .height('100%')
1315          .backgroundColor('rgb(213,213,213)')
1316          .onReady(() => {
1317            this.context.font = '50px sans-serif'
1318            this.context.fillText("Hello World!", 20, 100)
1319            this.context.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200)
1320        })
1321      }
1322      .width('100%')
1323      .height('100%')
1324    }
1325  }
1326  ```
1327
1328  ![measureText](figures/measureText.jpg)
1329
1330
1331### stroke
1332
1333stroke(): void
1334
1335Strokes (outlines) this path.
1336
1337**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1338
1339**Atomic service API**: This API can be used in atomic services since API version 11.
1340
1341**System capability**: SystemCapability.ArkUI.ArkUI.Full
1342
1343**Example**
1344
1345  ```ts
1346  // xxx.ets
1347  @Entry
1348  @Component
1349  struct Stroke {
1350    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1351    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1352
1353    build() {
1354      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1355        Canvas(this.context)
1356          .width('100%')
1357          .height('100%')
1358          .backgroundColor('#ffff00')
1359          .onReady(() => {
1360            this.context.moveTo(125, 25)
1361            this.context.lineTo(125, 105)
1362            this.context.lineTo(175, 105)
1363            this.context.lineTo(175, 25)
1364            this.context.strokeStyle = 'rgb(255,0,0)'
1365            this.context.stroke()
1366          })
1367      }
1368      .width('100%')
1369      .height('100%')
1370    }
1371  }
1372  ```
1373
1374  ![en-us_image_0000001238832389](figures/en-us_image_0000001238832389.png)
1375
1376### stroke
1377
1378stroke(path: Path2D): void
1379
1380Strokes (outlines) a specified path.
1381
1382**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1383
1384**Atomic service API**: This API can be used in atomic services since API version 11.
1385
1386**System capability**: SystemCapability.ArkUI.ArkUI.Full
1387
1388**Parameters**
1389
1390| Name  | Type     | Mandatory  | Description    |
1391| ---- | ---------------------------------------- | ---- | ------------ |
1392| path | [Path2D](ts-components-canvas-path2d.md) | Yes| A **Path2D** path to draw.|
1393
1394 **Example**
1395
1396  ```ts
1397  // xxx.ets
1398  @Entry
1399  @Component
1400  struct Stroke {
1401    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1402    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1403    private path2Da: Path2D = new Path2D()
1404
1405    build() {
1406      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1407        Canvas(this.context)
1408          .width('100%')
1409          .height('100%')
1410          .backgroundColor('#ffff00')
1411          .onReady(() => {
1412            this.path2Da.moveTo(25, 25)
1413            this.path2Da.lineTo(25, 105)
1414            this.path2Da.lineTo(75, 105)
1415            this.path2Da.lineTo(75, 25)
1416            this.context.strokeStyle = 'rgb(0,0,255)'
1417            this.context.stroke(this.path2Da)
1418          })
1419      }
1420      .width('100%')
1421      .height('100%')
1422    }
1423  }
1424  ```
1425
1426  ![en-us_image_0000001238832389](figures/en-us_image_0000001238832390.png)
1427
1428### beginPath
1429
1430beginPath(): void
1431
1432Creates a drawing path.
1433
1434**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1435
1436**Atomic service API**: This API can be used in atomic services since API version 11.
1437
1438**System capability**: SystemCapability.ArkUI.ArkUI.Full
1439
1440**Example**
1441
1442  ```ts
1443  // xxx.ets
1444  @Entry
1445  @Component
1446  struct BeginPath {
1447    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1448    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1449
1450    build() {
1451      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1452        Canvas(this.context)
1453          .width('100%')
1454          .height('100%')
1455          .backgroundColor('#ffff00')
1456          .onReady(() =>{
1457            this.context.beginPath()
1458            this.context.lineWidth = 6
1459            this.context.strokeStyle = '#0000ff'
1460            this.context.moveTo(15, 80)
1461            this.context.lineTo(280, 160)
1462            this.context.stroke()
1463          })
1464      }
1465      .width('100%')
1466      .height('100%')
1467    }
1468  }
1469  ```
1470
1471  ![en-us_image_0000001238712417](figures/en-us_image_0000001238712417.png)
1472
1473
1474### moveTo
1475
1476moveTo(x: number, y: number): void
1477
1478Moves a drawing path to a target position on the canvas.
1479
1480**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1481
1482**Atomic service API**: This API can be used in atomic services since API version 11.
1483
1484**System capability**: SystemCapability.ArkUI.ArkUI.Full
1485
1486**Parameters**
1487
1488| Name  | Type    | Mandatory  | Description       |
1489| ---- | ------ | ---- | --------- |
1490| x    | number | Yes   | X coordinate of the target position.<br>Default unit: vp|
1491| y    | number | Yes   | Y coordinate of the target position.<br>Default unit: vp|
1492
1493**Example**
1494
1495  ```ts
1496  // xxx.ets
1497  @Entry
1498  @Component
1499  struct MoveTo {
1500    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1501    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1502
1503    build() {
1504      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1505        Canvas(this.context)
1506          .width('100%')
1507          .height('100%')
1508          .backgroundColor('#ffff00')
1509          .onReady(() =>{
1510            this.context.beginPath()
1511            this.context.moveTo(10, 10)
1512            this.context.lineTo(280, 160)
1513            this.context.stroke()
1514          })
1515      }
1516      .width('100%')
1517      .height('100%')
1518    }
1519  }
1520  ```
1521
1522  ![en-us_image_0000001194192438](figures/en-us_image_0000001194192438.png)
1523
1524
1525### lineTo
1526
1527lineTo(x: number, y: number): void
1528
1529Connects the current point to a target position using a straight line.
1530
1531**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1532
1533**Atomic service API**: This API can be used in atomic services since API version 11.
1534
1535**System capability**: SystemCapability.ArkUI.ArkUI.Full
1536
1537**Parameters**
1538
1539| Name  | Type    | Mandatory  | Description       |
1540| ---- | ------ | ---- | --------- |
1541| x    | number | Yes   | X coordinate of the target position.<br>Default unit: vp|
1542| y    | number | Yes   | Y coordinate of the target position.<br>Default unit: vp|
1543
1544**Example**
1545
1546  ```ts
1547  // xxx.ets
1548  @Entry
1549  @Component
1550  struct LineTo {
1551    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1552    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1553
1554    build() {
1555      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1556        Canvas(this.context)
1557          .width('100%')
1558          .height('100%')
1559          .backgroundColor('#ffff00')
1560          .onReady(() =>{
1561            this.context.beginPath()
1562            this.context.moveTo(10, 10)
1563            this.context.lineTo(280, 160)
1564            this.context.stroke()
1565          })
1566      }
1567      .width('100%')
1568      .height('100%')
1569    }
1570  }
1571  ```
1572
1573  ![en-us_image_0000001194352438](figures/en-us_image_0000001194352438.png)
1574
1575
1576### closePath
1577
1578closePath(): void
1579
1580Draws a closed path.
1581
1582**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1583
1584**Atomic service API**: This API can be used in atomic services since API version 11.
1585
1586**System capability**: SystemCapability.ArkUI.ArkUI.Full
1587
1588**Example**
1589
1590  ```ts
1591  // xxx.ets
1592  @Entry
1593  @Component
1594  struct ClosePath {
1595    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1596    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1597
1598    build() {
1599      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1600        Canvas(this.context)
1601          .width('100%')
1602          .height('100%')
1603          .backgroundColor('#ffff00')
1604          .onReady(() =>{
1605              this.context.beginPath()
1606              this.context.moveTo(30, 30)
1607              this.context.lineTo(110, 30)
1608              this.context.lineTo(70, 90)
1609              this.context.closePath()
1610              this.context.stroke()
1611          })
1612      }
1613      .width('100%')
1614      .height('100%')
1615    }
1616  }
1617  ```
1618
1619  ![en-us_image_0000001238952379](figures/en-us_image_0000001238952379.png)
1620
1621
1622### createPattern
1623
1624createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | null
1625
1626Creates a pattern for image filling based on a specified source image and repetition mode.
1627
1628**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1629
1630**Atomic service API**: This API can be used in atomic services since API version 11.
1631
1632**System capability**: SystemCapability.ArkUI.ArkUI.Full
1633
1634**Parameters**
1635
1636| Name | Type | Mandatory | Description |
1637| ---------- | ---------- | ---- | ---------------------------------------- |
1638| image  | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | Source image. For details, see **ImageBitmap**.|
1639| repetition | string \| null  | Yes | Repetition mode.<br>**'repeat'**: The image is repeated along both the x-axis and y-axis.<br>**'repeat-x'**: The image is repeated along the x-axis.<br>**'repeat-y'**: The image is repeated along the y-axis.<br>**'no-repeat'**: The image is not repeated.<br>**'clamp'**: Coordinates outside the original bounds are clamped to the edge of the image.<br>**'mirror'**: The image is mirrored with each repetition along the x-axis and y-axis.|
1640
1641**Return value**
1642
1643| Type                                      | Description                     |
1644| ---------------------------------------- | ----------------------- |
1645| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) \| null | Created pattern for image filling based on a specified source image and repetition mode.|
1646
1647**Example**
1648
1649  ```ts
1650  // xxx.ets
1651  @Entry
1652  @Component
1653  struct CreatePattern {
1654    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1655    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1656    private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
1657
1658    build() {
1659      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1660        Canvas(this.context)
1661          .width('100%')
1662          .height('100%')
1663          .backgroundColor('#ffff00')
1664          .onReady(() =>{
1665            let pattern = this.context.createPattern(this.img, 'repeat')
1666            if (pattern) {
1667              this.context.fillStyle = pattern
1668            }
1669            this.context.fillRect(0, 0, 200, 200)
1670          })
1671      }
1672      .width('100%')
1673      .height('100%')
1674    }
1675  }
1676  ```
1677
1678  ![en-us_image_0000001194032460](figures/en-us_image_0000001194032460.png)
1679
1680
1681### bezierCurveTo
1682
1683bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
1684
1685Draws a cubic Bezier curve on the canvas.
1686
1687**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1688
1689**Atomic service API**: This API can be used in atomic services since API version 11.
1690
1691**System capability**: SystemCapability.ArkUI.ArkUI.Full
1692
1693**Parameters**
1694
1695| Name  | Type    | Mandatory  | Description |
1696| ---- | ------ | ---- | -------------- |
1697| cp1x | number | Yes | X coordinate of the first parameter of the bezier curve.<br>Default unit: vp|
1698| cp1y | number | Yes | Y coordinate of the first parameter of the bezier curve.<br>Default unit: vp|
1699| cp2x | number | Yes | X coordinate of the second parameter of the bezier curve.<br>Default unit: vp|
1700| cp2y | number | Yes | Y coordinate of the second parameter of the bezier curve.<br>Default unit: vp|
1701| x    | number | Yes | X coordinate of the end point on the bezier curve.<br>Default unit: vp|
1702| y    | number | Yes | Y coordinate of the end point on the bezier curve.<br>Default unit: vp|
1703
1704**Example**
1705
1706  ```ts
1707  // xxx.ets
1708  @Entry
1709  @Component
1710  struct BezierCurveTo {
1711    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1712    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1713
1714    build() {
1715      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1716        Canvas(this.context)
1717          .width('100%')
1718          .height('100%')
1719          .backgroundColor('#ffff00')
1720          .onReady(() =>{
1721            this.context.beginPath()
1722            this.context.moveTo(10, 10)
1723            this.context.bezierCurveTo(20, 100, 200, 100, 200, 20)
1724            this.context.stroke()
1725          })
1726      }
1727      .width('100%')
1728      .height('100%')
1729    }
1730  }
1731  ```
1732
1733  ![en-us_image_0000001239032415](figures/en-us_image_0000001239032415.png)
1734
1735
1736### quadraticCurveTo
1737
1738quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
1739
1740Draws a quadratic curve on the canvas.
1741
1742**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1743
1744**Atomic service API**: This API can be used in atomic services since API version 11.
1745
1746**System capability**: SystemCapability.ArkUI.ArkUI.Full
1747
1748**Parameters**
1749
1750| Name  | Type    | Mandatory  | Description         |
1751| ---- | ------ | ---- | ----------- |
1752| cpx  | number | Yes   | X coordinate of the bezier curve parameter.<br>Default unit: vp|
1753| cpy  | number | Yes   | Y coordinate of the bezier curve parameter.<br>Default unit: vp|
1754| x    | number | Yes   | X coordinate of the end point on the bezier curve.<br>Default unit: vp|
1755| y    | number | Yes   | Y coordinate of the end point on the bezier curve.<br>Default unit: vp|
1756
1757**Example**
1758
1759  ```ts
1760  // xxx.ets
1761  @Entry
1762  @Component
1763  struct QuadraticCurveTo {
1764    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1765    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1766
1767    build() {
1768      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1769        Canvas(this.context)
1770          .width('100%')
1771          .height('100%')
1772          .backgroundColor('#ffff00')
1773          .onReady(() =>{
1774            this.context.beginPath()
1775            this.context.moveTo(20, 20)
1776            this.context.quadraticCurveTo(100, 100, 200, 20)
1777            this.context.stroke()
1778        })
1779      }
1780      .width('100%')
1781      .height('100%')
1782    }
1783  }
1784  ```
1785
1786  ![en-us_image_0000001193872494](figures/en-us_image_0000001193872494.png)
1787
1788
1789### arc
1790
1791arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
1792
1793Draws an arc on the canvas.
1794
1795**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1796
1797**Atomic service API**: This API can be used in atomic services since API version 11.
1798
1799**System capability**: SystemCapability.ArkUI.ArkUI.Full
1800
1801**Parameters**
1802
1803| Name      | Type     | Mandatory  | Description        |
1804| ---------------- | ------- | ---- | ---------- |
1805| x                | number  | Yes | X coordinate of the center point of the arc.<br>Default unit: vp|
1806| y                | number  | Yes | Y coordinate of the center point of the arc.<br>Default unit: vp|
1807| radius           | number  | Yes | Radius of the arc.<br>Default unit: vp|
1808| startAngle       | number  | Yes | Start radian of the arc.<br>Unit: radian|
1809| endAngle         | number  | Yes | End radian of the arc.<br>Unit: radian|
1810| counterclockwise | boolean | No | Whether to draw the arc counterclockwise.<br>**true**: Draw the arc counterclockwise.<br>**false**: Draw the arc clockwise.<br>Default value: **false**|
1811
1812**Example**
1813
1814  ```ts
1815  // xxx.ets
1816  @Entry
1817  @Component
1818  struct Arc {
1819    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1820    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1821
1822    build() {
1823      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1824        Canvas(this.context)
1825          .width('100%')
1826          .height('100%')
1827          .backgroundColor('#ffff00')
1828          .onReady(() =>{
1829            this.context.beginPath()
1830            this.context.arc(100, 75, 50, 0, 6.28)
1831            this.context.stroke()
1832          })
1833      }
1834      .width('100%')
1835      .height('100%')
1836    }
1837  }
1838  ```
1839
1840  ![en-us_image_0000001238832391](figures/en-us_image_0000001238832391.jpeg)
1841
1842
1843### arcTo
1844
1845arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
1846
1847Creates a circular arc using the given control points and radius.
1848
1849**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1850
1851**Atomic service API**: This API can be used in atomic services since API version 11.
1852
1853**System capability**: SystemCapability.ArkUI.ArkUI.Full
1854
1855**Parameters**
1856
1857| Name    | Type    | Mandatory  | Description         |
1858| ------ | ------ | ---- | --------------- |
1859| x1     | number | Yes   | X coordinate of the first control point.<br>Default unit: vp|
1860| y1     | number | Yes   | Y coordinate of the first control point.<br>Default unit: vp|
1861| x2     | number | Yes   | X coordinate of the second control point.<br>Default unit: vp|
1862| y2     | number | Yes   | Y coordinate of the second control point.<br>Default unit: vp|
1863| radius | number | Yes   | Radius of the arc.<br>Default unit: vp|
1864
1865**Example**
1866
1867  ```ts
1868  // xxx.ets
1869  @Entry
1870  @Component
1871  struct ArcTo {
1872    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1873    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1874
1875    build() {
1876      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1877        Canvas(this.context)
1878          .width('100%')
1879          .height('100%')
1880          .backgroundColor('#ffff00')
1881          .onReady(() =>{
1882            // Tangent
1883            this.context.beginPath()
1884            this.context.strokeStyle = '#808080'
1885            this.context.lineWidth = 1.5;
1886            this.context.moveTo(360, 20);
1887            this.context.lineTo(360, 170);
1888            this.context.lineTo(110, 170);
1889            this.context.stroke();
1890
1891            // Arc
1892            this.context.beginPath()
1893            this.context.strokeStyle = '#000000'
1894            this.context.lineWidth = 3;
1895            this.context.moveTo(360, 20)
1896            this.context.arcTo(360, 170, 110, 170, 150)
1897            this.context.stroke()
1898
1899            // Start point
1900            this.context.beginPath();
1901            this.context.fillStyle = '#00ff00';
1902            this.context.arc(360, 20, 4, 0, 2 * Math.PI);
1903            this.context.fill();
1904
1905            // Control points
1906            this.context.beginPath();
1907            this.context.fillStyle = '#ff0000';
1908            this.context.arc(360, 170, 4, 0, 2 * Math.PI);
1909            this.context.arc(110, 170, 4, 0, 2 * Math.PI);
1910            this.context.fill();
1911          })
1912      }
1913      .width('100%')
1914      .height('100%')
1915    }
1916  }
1917  ```
1918
1919  ![en-us_image_0000001238712419](figures/en-us_image_0000001238712419.png)
1920
1921  > In this example, the arc created by **arcTo()** is black, and the two tangents of the arc are gray. The control points are marked in red, and the start point is indicated in green.
1922  >
1923  > You can visualize two tangents: One tangent extends from the start point to the first control point, and the other tangent extends from the first control point to the second control point. The **arcTo()** API creates an arc between these two tangents, ensuring that the arc is tangent to both lines at the points of contact.
1924
1925
1926### ellipse
1927
1928ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
1929
1930Draws an ellipse in the specified rectangular region on the canvas.
1931
1932**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1933
1934**Atomic service API**: This API can be used in atomic services since API version 11.
1935
1936**System capability**: SystemCapability.ArkUI.ArkUI.Full
1937
1938**Parameters**
1939
1940| Name              | Type     | Mandatory  | Description                                      |
1941| ---------------- | ------- | ---- | ---------------------------------------- |
1942| x                | number  | Yes| X coordinate of the ellipse center.<br>Default unit: vp|
1943| y                | number  | Yes| Y coordinate of the ellipse center.<br>Default unit: vp|
1944| radiusX          | number  | Yes| Radius of the ellipse on the x-axis.<br>Default unit: vp|
1945| radiusY          | number  | Yes| Radius of the ellipse on the y-axis.<br>Default unit: vp|
1946| rotation         | number  | Yes| Rotation angle of the ellipse.<br>Unit: radian|
1947| startAngle       | number  | Yes| Angle of the start point for drawing the ellipse.<br>Unit: radian|
1948| endAngle         | number  | Yes| Angle of the end point for drawing the ellipse.<br>Unit: radian|
1949| counterclockwise | boolean | No| Whether to draw the ellipse in the counterclockwise direction.<br>**true**: Draw the arc counterclockwise.<br>**false**: Draw the arc clockwise.<br>Default value: **false**|
1950
1951**Example**
1952
1953  ```ts
1954  // xxx.ets
1955  @Entry
1956  @Component
1957  struct CanvasExample {
1958    private settings: RenderingContextSettings = new RenderingContextSettings(true)
1959    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
1960
1961    build() {
1962      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
1963        Canvas(this.context)
1964          .width('100%')
1965          .height('100%')
1966          .backgroundColor('#ffff00')
1967          .onReady(() =>{
1968            this.context.beginPath()
1969            this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2, false)
1970            this.context.stroke()
1971            this.context.beginPath()
1972            this.context.ellipse(200, 300, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2, true)
1973            this.context.stroke()
1974          })
1975      }
1976      .width('100%')
1977      .height('100%')
1978    }
1979  }
1980  ```
1981
1982  ![en-us_image_0000001194192440](figures/en-us_image_0000001194192440.jpeg)
1983
1984
1985### rect
1986
1987rect(x: number, y: number, w: number, h: number): void
1988
1989Creates a rectangle on the canvas.
1990
1991**Widget capability**: This API can be used in ArkTS widgets since API version 9.
1992
1993**Atomic service API**: This API can be used in atomic services since API version 11.
1994
1995**System capability**: SystemCapability.ArkUI.ArkUI.Full
1996
1997**Parameters**
1998
1999| Name  | Type    | Mandatory  | Description           |
2000| ---- | ------ | ---- | ------------- |
2001| x    | number | Yes   | X coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
2002| y    | number | Yes   | Y coordinate of the upper left corner of the rectangle.<br>Default unit: vp|
2003| w    | number | Yes   | Width of the rectangle.<br>Default unit: vp|
2004| h    | number | Yes   | Height of the rectangle.<br>Default unit: vp|
2005
2006**Example**
2007
2008  ```ts
2009  // xxx.ets
2010  @Entry
2011  @Component
2012  struct CanvasExample {
2013    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2014    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2015
2016    build() {
2017      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2018        Canvas(this.context)
2019          .width('100%')
2020          .height('100%')
2021          .backgroundColor('#ffff00')
2022          .onReady(() =>{
2023            this.context.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
2024            this.context.stroke()
2025          })
2026      }
2027      .width('100%')
2028      .height('100%')
2029    }
2030  }
2031  ```
2032
2033  ![en-us_image_0000001194352440](figures/en-us_image_0000001194352440.jpeg)
2034
2035
2036### fill
2037
2038fill(fillRule?: CanvasFillRule): void
2039
2040Fills the area inside a closed path on the canvas.
2041
2042**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2043
2044**Atomic service API**: This API can be used in atomic services since API version 11.
2045
2046**System capability**: SystemCapability.ArkUI.ArkUI.Full
2047
2048**Parameters**
2049
2050| Name| Type            | Mandatory  | Description   |
2051| -------- | -------------- | ---- | ---------------------------------------- |
2052| fillRule | [CanvasFillRule](#canvasfillrule) | No   | Rule by which to determine whether a point is inside or outside the area to fill.<br>The options are **"nonzero"** and **"evenodd"**.<br>Default value: **"nonzero"**|
2053
2054
2055**Example**
2056
2057  ```ts
2058  // xxx.ets
2059  @Entry
2060  @Component
2061  struct Fill {
2062    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2063    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2064
2065    build() {
2066      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2067        Canvas(this.context)
2068          .width('100%')
2069          .height('100%')
2070          .backgroundColor('#ffff00')
2071          .onReady(() =>{
2072            this.context.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
2073            this.context.fill()
2074          })
2075      }
2076      .width('100%')
2077      .height('100%')
2078    }
2079  }
2080  ```
2081
2082  ![en-us_image_0000001238952381](figures/en-us_image_0000001238952381.png)
2083
2084
2085fill(path: Path2D, fillRule?: CanvasFillRule): void
2086
2087Fills the area inside a closed path on the canvas.
2088
2089**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2090
2091**Atomic service API**: This API can be used in atomic services since API version 11.
2092
2093**System capability**: SystemCapability.ArkUI.ArkUI.Full
2094
2095**Parameters**
2096
2097| Name   | Type            | Mandatory  | Description |
2098| -------- | -------------- | ---- | ---------------------------------------- |
2099| path     | [Path2D](ts-components-canvas-path2d.md)         | Yes | A **Path2D** path to fill.                             |
2100| fillRule | [CanvasFillRule](#canvasfillrule) | No   | Rule by which to determine whether a point is inside or outside the area to fill.<br>The options are **"nonzero"** and **"evenodd"**.<br>Default value: **"nonzero"**|
2101
2102
2103**Example**
2104
2105```ts
2106// xxx.ets
2107@Entry
2108@Component
2109struct Fill {
2110  private settings: RenderingContextSettings = new RenderingContextSettings(true)
2111  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2112
2113  build() {
2114    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2115      Canvas(this.context)
2116        .width('100%')
2117        .height('100%')
2118        .backgroundColor('#ffff00')
2119        .onReady(() =>{
2120          let region = new Path2D()
2121          region.moveTo(30, 90)
2122          region.lineTo(110, 20)
2123          region.lineTo(240, 130)
2124          region.lineTo(60, 130)
2125          region.lineTo(190, 20)
2126          region.lineTo(270, 90)
2127          region.closePath()
2128          // Fill path
2129          this.context.fillStyle = '#00ff00'
2130          this.context.fill(region, "evenodd")
2131        })
2132    }
2133    .width('100%')
2134    .height('100%')
2135  }
2136}
2137```
2138
2139 ![en-us_image_000000127777774](figures/en-us_image_000000127777774.jpg)
2140
2141
2142### clip
2143
2144clip(fillRule?: CanvasFillRule): void
2145
2146Sets the current path to a clipping area.
2147
2148**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2149
2150**Atomic service API**: This API can be used in atomic services since API version 11.
2151
2152**System capability**: SystemCapability.ArkUI.ArkUI.Full
2153
2154**Parameters**
2155
2156| Name      | Type            | Mandatory  | Description                           |
2157| -------- | -------------- | ---- | ---------------------------------------- |
2158| fillRule | [CanvasFillRule](#canvasfillrule) | No| Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.<br>Default value: **"nonzero"**|
2159
2160**Example**
2161
2162  ```ts
2163  // xxx.ets
2164  @Entry
2165  @Component
2166  struct Clip {
2167    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2168    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2169
2170    build() {
2171      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2172        Canvas(this.context)
2173          .width('100%')
2174          .height('100%')
2175          .backgroundColor('#ffff00')
2176          .onReady(() =>{
2177            this.context.rect(0, 0, 100, 200)
2178            this.context.stroke()
2179            this.context.clip()
2180            this.context.fillStyle = "rgb(255,0,0)"
2181            this.context.fillRect(0, 0, 200, 200)
2182          })
2183      }
2184      .width('100%')
2185      .height('100%')
2186    }
2187  }
2188  ```
2189
2190  ![en-us_image_0000001194032462](figures/en-us_image_0000001194032462.png)
2191
2192
2193clip(path: Path2D, fillRule?: CanvasFillRule): void
2194
2195Sets the current path to a clipping area.
2196
2197**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2198
2199**Atomic service API**: This API can be used in atomic services since API version 11.
2200
2201**System capability**: SystemCapability.ArkUI.ArkUI.Full
2202
2203**Parameters**
2204
2205| Name     | Type            | Mandatory  | Description         |
2206| -------- | -------------- | ---- | ---------------------------------------- |
2207| path     | [Path2D](ts-components-canvas-path2d.md)         | Yes   | A **Path2D** path to use as a clipping area.                             |
2208| fillRule | [CanvasFillRule](#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.<br>Default value: **"nonzero"**|
2209
2210
2211**Example**
2212
2213  ```ts
2214  // xxx.ets
2215  @Entry
2216  @Component
2217  struct Clip {
2218    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2219    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2220    build() {
2221      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2222        Canvas(this.context)
2223          .width('100%')
2224          .height('100%')
2225          .backgroundColor('#ffff00')
2226          .onReady(() =>{
2227            let region = new Path2D()
2228            region.moveTo(30, 90)
2229            region.lineTo(110, 20)
2230            region.lineTo(240, 130)
2231            region.lineTo(60, 130)
2232            region.lineTo(190, 20)
2233            region.lineTo(270, 90)
2234            region.closePath()
2235            this.context.clip(region,"evenodd")
2236            this.context.fillStyle = "rgb(0,255,0)"
2237            this.context.fillRect(0, 0, this.context.width, this.context.height)
2238          })
2239      }
2240      .width('100%')
2241      .height('100%')
2242    }
2243  }
2244  ```
2245
2246  ![en-us_image_000000127777779](figures/en-us_image_000000127777779.jpg)
2247
2248
2249### reset<sup>12+</sup>
2250
2251reset(): void
2252
2253Resets this **CanvasRenderingContext2D** object to its default state and clears the background buffer, drawing state stack, defined paths, and styles.
2254
2255**System capability**: SystemCapability.ArkUI.ArkUI.Full
2256
2257**Example**
2258
2259  ```ts
2260  // xxx.ets
2261  @Entry
2262  @Component
2263  struct Reset {
2264    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2265    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2266
2267    build() {
2268      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2269        Canvas(this.context)
2270          .width('100%')
2271          .height('100%')
2272          .backgroundColor('#ffff00')
2273          .onReady(() =>{
2274            this.context.fillStyle = '#0000ff'
2275            this.context.fillRect(20, 20, 150, 100)
2276            this.context.reset()
2277            this.context.fillRect(20, 150, 150, 100)
2278          })
2279      }
2280      .width('100%')
2281      .height('100%')
2282    }
2283  }
2284  ```
2285
2286  ![en-us_image_0000001239032460](figures/en-us_image_0000001239032460.png)
2287
2288
2289### saveLayer<sup>12+</sup>
2290
2291saveLayer(): void
2292
2293Saves this layer.
2294
2295**System capability**: SystemCapability.ArkUI.ArkUI.Full
2296
2297**Example**
2298
2299  ```ts
2300  // xxx.ets
2301  @Entry
2302  @Component
2303  struct saveLayer {
2304  private settings: RenderingContextSettings = new RenderingContextSettings(true)
2305  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2306
2307  build() {
2308    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2309      Canvas(this.context)
2310        .width('100%')
2311        .height('100%')
2312        .backgroundColor('#ffff00')
2313        .onReady(() =>{
2314          this.context.fillStyle = "#0000ff"
2315          this.context.fillRect(50,100,300,100)
2316          this.context.fillStyle = "#00ffff"
2317          this.context.fillRect(50,150,300,100)
2318          this.context.globalCompositeOperation = 'destination-over'
2319          this.context.saveLayer()
2320          this.context.globalCompositeOperation = 'source-over'
2321          this.context.fillStyle = "#ff0000"
2322          this.context.fillRect(100,50,100,300)
2323          this.context.fillStyle = "#00ff00"
2324          this.context.fillRect(150,50,100,300)
2325          this.context.restoreLayer()
2326        })
2327    }
2328    .width('100%')
2329    .height('100%')
2330  }
2331  }
2332
2333  ```
2334   ![en-us_image_CanvasSavelayer](figures/en-us_image_CanvasSavelayer.png)
2335
2336### restoreLayer<sup>12+</sup>
2337
2338restoreLayer(): void
2339
2340Restores the image transformation and cropping state to the state before **saveLayer**, and then draws the layer onto the canvas. For the sample code, see the code for **saveLayer**.
2341
2342**System capability**: SystemCapability.ArkUI.ArkUI.Full
2343
2344### resetTransform
2345
2346resetTransform(): void
2347
2348Resets the current transform to the identity matrix.
2349
2350**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2351
2352**Atomic service API**: This API can be used in atomic services since API version 11.
2353
2354**System capability**: SystemCapability.ArkUI.ArkUI.Full
2355
2356**Example**
2357
2358  ```ts
2359  // xxx.ets
2360  @Entry
2361  @Component
2362  struct ResetTransform {
2363    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2364    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2365
2366    build() {
2367      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2368        Canvas(this.context)
2369          .width('100%')
2370          .height('100%')
2371          .backgroundColor('#ffff00')
2372          .onReady(() =>{
2373            this.context.setTransform(1,0.5, -0.5, 1, 10, 10)
2374            this.context.fillStyle = 'rgb(0,0,255)'
2375            this.context.fillRect(0, 0, 100, 100)
2376            this.context.resetTransform()
2377            this.context.fillStyle = 'rgb(255,0,0)'
2378            this.context.fillRect(0, 0, 100, 100)
2379          })
2380      }
2381      .width('100%')
2382      .height('100%')
2383    }
2384  }
2385  ```
2386
2387  ![en-us_image_0000001239032417](figures/en-us_image_ResetTransform.png)
2388
2389### rotate
2390
2391rotate(angle: number): void
2392
2393Rotates a canvas clockwise around its coordinate axes.
2394
2395**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2396
2397**Atomic service API**: This API can be used in atomic services since API version 11.
2398
2399**System capability**: SystemCapability.ArkUI.ArkUI.Full
2400
2401**Parameters**
2402
2403| Name   | Type    | Mandatory  | Description                                      |
2404| ----- | ------ | ---- |  ---------------------------------------- |
2405| angle | number | Yes  | Clockwise rotation angle. You can convert degrees to radians using the following formula: degree * Math.PI/180.<br>Unit: radian|
2406
2407**Example**
2408
2409  ```ts
2410  // xxx.ets
2411  @Entry
2412  @Component
2413  struct Rotate {
2414    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2415    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2416
2417    build() {
2418      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2419        Canvas(this.context)
2420          .width('100%')
2421          .height('100%')
2422          .backgroundColor('#ffff00')
2423          .onReady(() =>{
2424            this.context.rotate(45 * Math.PI / 180)
2425            this.context.fillRect(70, 20, 50, 50)
2426          })
2427      }
2428      .width('100%')
2429      .height('100%')
2430    }
2431  }
2432  ```
2433
2434  ![en-us_image_0000001239032417](figures/en-us_image_0000001239032417.png)
2435
2436
2437### scale
2438
2439scale(x: number, y: number): void
2440
2441Scales the canvas based on the given scale factors.
2442
2443**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2444
2445**Atomic service API**: This API can be used in atomic services since API version 11.
2446
2447**System capability**: SystemCapability.ArkUI.ArkUI.Full
2448
2449**Parameters**
2450
2451| Name  | Type    | Mandatory | Description   |
2452| ---- | ------ | ---- | ----------- |
2453| x    | number | Yes | Horizontal scale factor.|
2454| y    | number | Yes | Vertical scale factor.|
2455
2456**Example**
2457
2458  ```ts
2459  // xxx.ets
2460  @Entry
2461  @Component
2462  struct Scale {
2463    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2464    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2465
2466    build() {
2467      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2468        Canvas(this.context)
2469          .width('100%')
2470          .height('100%')
2471          .backgroundColor('#ffff00')
2472          .onReady(() =>{
2473            this.context.lineWidth = 3
2474            this.context.strokeRect(30, 30, 50, 50)
2475            this.context.scale(2, 2) // Scale to 200%
2476            this.context.strokeRect(30, 30, 50, 50)
2477          })
2478      }
2479      .width('100%')
2480      .height('100%')
2481    }
2482  }
2483  ```
2484
2485  ![en-us_image_0000001193872498](figures/en-us_image_0000001193872498.png)
2486
2487
2488### transform
2489
2490transform(a: number, b: number, c: number, d: number, e: number, f: number): void
2491
2492Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects.
2493
2494**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2495
2496**Atomic service API**: This API can be used in atomic services since API version 11.
2497
2498**System capability**: SystemCapability.ArkUI.ArkUI.Full
2499
2500> **NOTE**
2501> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation.
2502>
2503> - x' = scaleX \* x + skewY \* y + translateX
2504>
2505> - y' = skewX \* x + scaleY \* y + translateY
2506
2507**Parameters**
2508
2509| Name  | Type    | Mandatory  | Description                  |
2510| ---- | ------ | ---- | -------------------- |
2511| a    | number | Yes | X-axis scale. |
2512| b    | number | Yes | Y-axis skew.  |
2513| c    | number | Yes | X-axis skew.  |
2514| d    | number | Yes | Y-axis scale. |
2515| e    | number | Yes | **translateX**: distance to translate on the x-axis.<br>Default unit: vp|
2516| f    | number | Yes | **translateY**: distance to translate on the y-axis.<br>Default unit: vp|
2517
2518**Example**
2519
2520  ```ts
2521  // xxx.ets
2522  @Entry
2523  @Component
2524  struct Transform {
2525    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2526    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2527
2528    build() {
2529      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2530        Canvas(this.context)
2531          .width('100%')
2532          .height('100%')
2533          .backgroundColor('#ffff00')
2534          .onReady(() => {
2535            this.context.fillStyle = 'rgb(0,0,0)'
2536            this.context.fillRect(0, 0, 100, 100)
2537            this.context.transform(1, 0.5, -0.5, 1, 10, 10)
2538            this.context.fillStyle = 'rgb(255,0,0)'
2539            this.context.fillRect(0, 0, 100, 100)
2540            this.context.transform(1, 0.5, -0.5, 1, 10, 10)
2541            this.context.fillStyle = 'rgb(0,0,255)'
2542            this.context.fillRect(0, 0, 100, 100)
2543          })
2544      }
2545      .width('100%')
2546      .height('100%')
2547    }
2548  }
2549  ```
2550
2551  ![transform](figures/transform.jpg)
2552
2553
2554### setTransform
2555
2556setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
2557
2558Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API.
2559
2560**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2561
2562**Atomic service API**: This API can be used in atomic services since API version 11.
2563
2564**System capability**: SystemCapability.ArkUI.ArkUI.Full
2565
2566**Parameters**
2567
2568| Name  | Type    | Mandatory  | Description   |
2569| ---- | ------ | ---- | -------------------- |
2570| a    | number | Yes| X-axis scale.|
2571| b    | number | Yes| Y-axis skew. |
2572| c    | number | Yes| X-axis skew. |
2573| d    | number | Yes| Y-axis scale.|
2574| e    | number | Yes| **translateX**: distance to translate on the x-axis.<br>Default unit: vp|
2575| f    | number | Yes| **translateY**: distance to translate on the y-axis.<br>Default unit: vp|
2576
2577**Example**
2578
2579  ```ts
2580  // xxx.ets
2581  @Entry
2582  @Component
2583  struct SetTransform {
2584    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2585    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2586
2587    build() {
2588      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2589        Canvas(this.context)
2590          .width('100%')
2591          .height('100%')
2592          .backgroundColor('#ffff00')
2593          .onReady(() =>{
2594            this.context.fillStyle = 'rgb(255,0,0)'
2595            this.context.fillRect(0, 0, 100, 100)
2596            this.context.setTransform(1,0.5, -0.5, 1, 10, 10)
2597            this.context.fillStyle = 'rgb(0,0,255)'
2598            this.context.fillRect(0, 0, 100, 100)
2599          })
2600      }
2601      .width('100%')
2602      .height('100%')
2603    }
2604  }
2605  ```
2606
2607  ![en-us_image_0000001238712421](figures/en-us_image_0000001238712421.png)
2608
2609setTransform(transform?: Matrix2D): void
2610
2611Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object.
2612
2613**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2614
2615**Atomic service API**: This API can be used in atomic services since API version 11.
2616
2617**System capability**: SystemCapability.ArkUI.ArkUI.Full
2618
2619**Parameters**
2620
2621| Name | Type| Mandatory| Description |
2622| --------- | ---------------------------------------- | ---- | ----- |
2623| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No| Transformation matrix.<br>Default value: **null**|
2624
2625**Example**
2626
2627  ```ts
2628  // xxx.ets
2629  @Entry
2630  @Component
2631  struct TransFormDemo {
2632    private settings: RenderingContextSettings = new RenderingContextSettings(true);
2633    private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.  settings);
2634    private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
2635
2636    build() {
2637      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2638        Text('context1');
2639        Canvas(this.context1)
2640          .width('230vp')
2641          .height('160vp')
2642          .backgroundColor('#ffff00')
2643          .onReady(() =>{
2644            this.context1.fillRect(100, 20, 50, 50);
2645            this.context1.setTransform(1, 0.5, -0.5, 1, 10, 10);
2646            this.context1.fillRect(100, 20, 50, 50);
2647          })
2648        Text('context2');
2649        Canvas(this.context2)
2650          .width('230vp')
2651          .height('160vp')
2652          .backgroundColor('#0ffff0')
2653          .onReady(() =>{
2654            this.context2.fillRect(100, 20, 50, 50);
2655            let storedTransform = this.context1.getTransform();
2656            this.context2.setTransform(storedTransform);
2657            this.context2.fillRect(100, 20, 50, 50);
2658          })
2659      }
2660      .width('100%')
2661      .height('100%')
2662    }
2663  }
2664  ```
2665
2666  ![en-us_image_0000001238712422.jpeg](figures/en-us_image_0000001238712422.jpeg)
2667
2668### getTransform
2669
2670getTransform(): Matrix2D
2671
2672Obtains the current transformation matrix being applied to the context.
2673
2674**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2675
2676**Atomic service API**: This API can be used in atomic services since API version 11.
2677
2678**System capability**: SystemCapability.ArkUI.ArkUI.Full
2679
2680**Return value**
2681
2682| Type                                      | Description   |
2683| ---------------------------------------- | ----- |
2684| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | **Matrix2D** object.|
2685
2686**Example**
2687
2688  ```ts
2689  // xxx.ets
2690  @Entry
2691  @Component
2692  struct TransFormDemo {
2693    private settings: RenderingContextSettings = new RenderingContextSettings(true);
2694    private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
2695    private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
2696
2697    build() {
2698      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2699        Text('context1');
2700        Canvas(this.context1)
2701          .width('230vp')
2702          .height('120vp')
2703          .backgroundColor('#ffff00')
2704          .onReady(() =>{
2705            this.context1.fillRect(50, 50, 50, 50);
2706            this.context1.setTransform(1.2, Math.PI/8, Math.PI/6, 0.5, 30, -25);
2707            this.context1.fillRect(50, 50, 50, 50);
2708          })
2709        Text('context2');
2710        Canvas(this.context2)
2711          .width('230vp')
2712          .height('120vp')
2713          .backgroundColor('#0ffff0')
2714          .onReady(() =>{
2715            this.context2.fillRect(50, 50, 50, 50);
2716            let storedTransform = this.context1.getTransform();
2717            console.log("Matrix [scaleX = " + storedTransform.scaleX + ", scaleY = " + storedTransform.scaleY +
2718            ", rotateX = " + storedTransform.rotateX + ", rotateY = " + storedTransform.rotateY +
2719            ", translateX = " + storedTransform.translateX + ", translateY = " + storedTransform.translateY + "]")
2720            this.context2.setTransform(storedTransform);
2721            this.context2.fillRect(50,50,50,50);
2722          })
2723      }
2724      .width('100%')
2725      .height('100%')
2726    }
2727  }
2728  ```
2729
2730  ![en-us_image_0000001219982726.png](figures/en-us_image_0000001219982726.png)
2731
2732### translate
2733
2734translate(x: number, y: number): void
2735
2736Moves the origin of the coordinate system.
2737
2738**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2739
2740**Atomic service API**: This API can be used in atomic services since API version 11.
2741
2742**System capability**: SystemCapability.ArkUI.ArkUI.Full
2743
2744**Parameters**
2745
2746| Name  | Type    | Mandatory  | Description|
2747| ---- | ------ | ---- | -------- |
2748| x    | number | Yes  | Distance to translate on the x-axis.<br>Default unit: vp|
2749| y    | number | Yes  | Distance to translate on the y-axis.<br>Default unit: vp|
2750
2751**Example**
2752
2753  ```ts
2754  // xxx.ets
2755  @Entry
2756  @Component
2757  struct Translate {
2758    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2759    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2760
2761    build() {
2762      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2763        Canvas(this.context)
2764          .width('100%')
2765          .height('100%')
2766          .backgroundColor('#ffff00')
2767          .onReady(() =>{
2768            this.context.fillRect(10, 10, 50, 50)
2769            this.context.translate(70, 70)
2770            this.context.fillRect(10, 10, 50, 50)
2771          })
2772      }
2773      .width('100%')
2774      .height('100%')
2775    }
2776  }
2777  ```
2778
2779  ![en-us_image_0000001194192446](figures/en-us_image_0000001194192446.png)
2780
2781
2782### drawImage
2783
2784drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void
2785
2786Draws an image on the canvas.
2787
2788**Widget capability**: This API can be used in ArkTS widgets since API version 9, except that **PixelMap** objects are not supported.
2789
2790**Atomic service API**: This API can be used in atomic services since API version 11.
2791
2792**System capability**: SystemCapability.ArkUI.ArkUI.Full
2793
2794**Parameters**
2795
2796| Name | Type | Mandatory | Description|
2797| ----- | ---------------------------------------- | ---- | ---------------------------------------- |
2798| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)| Yes   | Image resource. For details, see **ImageBitmap** or PixelMap.           |
2799| dx    | number                                   | Yes | X coordinate of the upper left corner of the drawing area on the canvas.<br>Default unit: vp|
2800| dy    | number                                   | Yes | Y coordinate of the upper left corner of the drawing area on the canvas.<br>Default unit: vp|
2801
2802drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dw: number, dh: number): void
2803
2804Draws an image on the canvas.
2805
2806**Widget capability**: This API can be used in ArkTS widgets since API version 9, except that **PixelMap** objects are not supported.
2807
2808**Atomic service API**: This API can be used in atomic services since API version 11.
2809
2810**System capability**: SystemCapability.ArkUI.ArkUI.Full
2811
2812**Parameters**
2813
2814| Name | Type | Mandatory | Description|
2815| ----- | ---------------------------------------- | ---- | ---------------------------------------- |
2816| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)| Yes   | Image resource. For details, see **ImageBitmap** or PixelMap.           |
2817| dx    | number                                   | Yes | X coordinate of the upper left corner of the drawing area on the canvas.<br>Default unit: vp|
2818| dy    | number                                   | Yes | Y coordinate of the upper left corner of the drawing area on the canvas.<br>Default unit: vp|
2819| dw    | number                                   | Yes | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.<br>Default unit: vp|
2820| dh    | number                                   | Yes | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.<br>Default unit: vp|
2821
2822drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void
2823
2824Draws an image on the canvas.
2825
2826**Widget capability**: This API can be used in ArkTS widgets since API version 9, except that **PixelMap** objects are not supported.
2827
2828**Atomic service API**: This API can be used in atomic services since API version 11.
2829
2830**System capability**: SystemCapability.ArkUI.ArkUI.Full
2831
2832**Parameters**
2833
2834| Name | Type | Mandatory | Description|
2835| ----- | ---------------------------------------- | ---- | ---------------------------------------- |
2836| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)| Yes   | Image resource. For details, see **ImageBitmap** or PixelMap.           |
2837| sx    | number                                   | Yes | X coordinate of the upper left corner of the rectangle used to crop the source image.<br>If the type of **image** is ImageBitmap, the default unit is vp.<br>If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later.|
2838| sy    | number                                   | Yes | Y coordinate of the upper left corner of the rectangle used to crop the source image.<br>If the type of **image** is ImageBitmap, the default unit is vp.<br>If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later. |
2839| sw    | number                                   | Yes | Target width to crop the source image.<br>If the type of **image** is ImageBitmap, the default unit is vp.<br>If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later. |
2840| sh    | number                                   | Yes | Target height to crop the source image.<br>If the type of **image** is ImageBitmap, the default unit is vp.<br>If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later. |
2841| dx    | number                                   | Yes | X coordinate of the upper left corner of the drawing area on the canvas.<br>Default unit: vp|
2842| dy    | number                                   | Yes | Y coordinate of the upper left corner of the drawing area on the canvas.<br>Default unit: vp|
2843| dw    | number                                   | Yes | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.<br>Default unit: vp|
2844| dh    | number                                   | Yes | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.<br>Default unit: vp|
2845
2846**Example**
2847
2848  ```ts
2849  // xxx.ets
2850  @Entry
2851  @Component
2852  struct ImageExample {
2853    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2854    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2855    private img: ImageBitmap = new ImageBitmap("common/images/example.jpg")
2856
2857    build() {
2858      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2859        Canvas(this.context)
2860          .width('100%')
2861          .height('100%')
2862          .backgroundColor('#ffff00')
2863          .onReady(() => {
2864            this.context.drawImage(this.img, 0, 0)
2865            this.context.drawImage(this.img, 0, 150, 300, 100)
2866            this.context.drawImage(this.img, 0, 0, 500, 500, 0, 300, 400, 200)
2867          })
2868      }
2869      .width('100%')
2870      .height('100%')
2871    }
2872  }
2873  ```
2874
2875  ![en-us_image_0000001194352442](figures/en-us_image_0000001194352441.png)
2876
2877
2878### createImageData
2879
2880createImageData(sw: number, sh: number): ImageData
2881
2882Creates a blank [ImageData](ts-components-canvas-imagedata.md) object of a specified size. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it. The example is the same as that of **putImageData**.
2883
2884**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2885
2886**Atomic service API**: This API can be used in atomic services since API version 11.
2887
2888**System capability**: SystemCapability.ArkUI.ArkUI.Full
2889
2890**Parameters**
2891
2892| Name  | Type    | Mandatory  | Description|
2893| ---- | ------ | ---- | ------------- |
2894| sw   | number | Yes| Width of the **ImageData** object.<br>Default unit: vp|
2895| sh   | number | Yes| Height of the **ImageData** object.<br>Default unit: vp|
2896
2897
2898createImageData(imageData: ImageData): ImageData
2899
2900Creates an [ImageData](ts-components-canvas-imagedata.md) object with the same width and height of an existing **ImageData** object. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it. The example is the same as that of **putImageData**.
2901
2902**Widget capability**: This API can be used in ArkTS widgets since API version 9.
2903
2904**Atomic service API**: This API can be used in atomic services since API version 11.
2905
2906**System capability**: SystemCapability.ArkUI.ArkUI.Full
2907
2908**Parameters**
2909
2910| Name| Type | Mandatory| Description |
2911| --------- | ---------------------------------------- | ---- | ----------------- |
2912| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes| Existing **ImageData** object.|
2913
2914  **Return value**
2915
2916| Type                                      | Description            |
2917| ---------------------------------------- | -------------- |
2918| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.|
2919
2920
2921### getPixelMap
2922
2923getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
2924
2925Obtains the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) object created with the pixels within the specified area on the canvas. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it.
2926
2927**Atomic service API**: This API can be used in atomic services since API version 11.
2928
2929**System capability**: SystemCapability.ArkUI.ArkUI.Full
2930
2931**Parameters**
2932
2933| Name  | Type    | Mandatory| Description|
2934| ---- | ------ | ---- | --------------- |
2935| sx   | number | Yes | X coordinate of the upper left corner of the output area.<br>Default unit: vp|
2936| sy   | number | Yes | Y coordinate of the upper left corner of the output area.<br>Default unit: vp|
2937| sw   | number | Yes | Width of the output area.<br>Default unit: vp|
2938| sh   | number | Yes | Height of the output area.<br>Default unit: vp|
2939
2940**Return value**
2941
2942| Type                                      | Description           |
2943| ---------------------------------------- | ------------- |
2944| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object.|
2945
2946**Example**
2947
2948> **NOTE**
2949>
2950> DevEco Studio Previewer does not support displaying content drawn using **setPixelMap**.
2951
2952  ```ts
2953  // xxx.ets
2954  @Entry
2955  @Component
2956  struct GetPixelMap {
2957    private settings: RenderingContextSettings = new RenderingContextSettings(true)
2958    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
2959    private img: ImageBitmap = new ImageBitmap("common/images/example.jpg")
2960
2961    build() {
2962      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
2963        Canvas(this.context)
2964          .width('100%')
2965          .height('100%')
2966          .backgroundColor('#ffff00')
2967          .onReady(() => {
2968            this.context.drawImage(this.img, 100, 100, 130, 130)
2969            let pixelmap = this.context.getPixelMap(150, 150, 130, 130)
2970            this.context.setPixelMap(pixelmap)
2971          })
2972      }
2973      .width('100%')
2974      .height('100%')
2975    }
2976  }
2977  ```
2978
2979  ![en-us_image_000000127777782](figures/en-us_image_000000127777782.png)
2980
2981### setPixelMap
2982
2983setPixelMap(value?: PixelMap): void
2984
2985Draws the input [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) object on the canvas. The example is the same as that of **getPixelMap**.
2986
2987**Atomic service API**: This API can be used in atomic services since API version 11.
2988
2989**System capability**: SystemCapability.ArkUI.ArkUI.Full
2990
2991 **Parameters**
2992
2993| Name  | Type    | Mandatory  | Description|
2994| ---- | ------ | ---- | --------------- |
2995|  value  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | No| **PixelMap** object that contains pixel values.<br>Default value: **null**|
2996
2997### getImageData
2998
2999getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
3000
3001Obtains the [ImageData](ts-components-canvas-imagedata.md) object created with the pixels within the specified area on the canvas. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it.
3002
3003**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3004
3005**Atomic service API**: This API can be used in atomic services since API version 11.
3006
3007**System capability**: SystemCapability.ArkUI.ArkUI.Full
3008
3009**Parameters**
3010
3011| Name| Type| Mandatory  | Description |
3012| ---- | ------ | ---- | --------------- |
3013| sx   | number | Yes| X coordinate of the upper left corner of the output area.<br>Default unit: vp|
3014| sy   | number | Yes| Y coordinate of the upper left corner of the output area.<br>Default unit: vp|
3015| sw   | number | Yes| Width of the output area.<br>Default unit: vp|
3016| sh   | number | Yes| Height of the output area.<br>Default unit: vp|
3017
3018  **Return value**
3019
3020| Type                                      | Description            |
3021| ---------------------------------------- | -------------- |
3022| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.|
3023
3024
3025**Example**
3026
3027  ```ts
3028  // xxx.ets
3029  @Entry
3030  @Component
3031  struct GetImageData {
3032    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3033    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3034    private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
3035
3036    build() {
3037      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3038        Canvas(this.context)
3039          .width('100%')
3040          .height('100%')
3041          .backgroundColor('#ffff00')
3042          .onReady(() =>{
3043            this.context.drawImage(this.img,0,0,130,130)
3044            let imagedata = this.context.getImageData(50,50,130,130)
3045            this.context.putImageData(imagedata,150,150)
3046          })
3047      }
3048      .width('100%')
3049      .height('100%')
3050    }
3051  }
3052  ```
3053
3054  ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
3055
3056
3057### putImageData
3058
3059putImageData(imageData: ImageData, dx: number | string, dy: number | string): void
3060
3061Puts an [ImageData](ts-components-canvas-imagedata.md) object onto a rectangular area on the canvas.
3062
3063**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3064
3065**Atomic service API**: This API can be used in atomic services since API version 11.
3066
3067**System capability**: SystemCapability.ArkUI.ArkUI.Full
3068
3069**Parameters**
3070
3071| Name| Type| Mandatory | Description|
3072| ----------- | ---------------------------------------- | ---- | ----------------------------- |
3073| imagedata   | [ImageData](ts-components-canvas-imagedata.md) | Yes   | **ImageData** object with pixels to put onto the canvas.|
3074| dx          | number \| string<sup>10+</sup> | Yes   | X-axis offset of the rectangular area on the canvas.<br>Default unit: vp|
3075| dy          | number \| string<sup>10+</sup> | Yes   | Y-axis offset of the rectangular area on the canvas.<br>Default unit: vp|
3076
3077putImageData(imageData: ImageData, dx: number | string, dy: number | string, dirtyX: number | string, dirtyY: number | string, dirtyWidth: number | string, dirtyHeight: number | string): void
3078
3079Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas.
3080
3081**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3082
3083**Atomic service API**: This API can be used in atomic services since API version 11.
3084
3085**System capability**: SystemCapability.ArkUI.ArkUI.Full
3086
3087**Parameters**
3088
3089| Name| Type| Mandatory | Description|
3090| ----------- | ---------------------------------------- | ---- | ----------------------------- |
3091| imagedata   | [ImageData](ts-components-canvas-imagedata.md) | Yes   | **ImageData** object with pixels to put onto the canvas.|
3092| dx          | number \| string<sup>10+</sup> | Yes   | X-axis offset of the rectangular area on the canvas.<br>Default unit: vp|
3093| dy          | number \| string<sup>10+</sup> | Yes   | Y-axis offset of the rectangular area on the canvas.<br>Default unit: vp|
3094| dirtyX      | number \| string<sup>10+</sup> | Yes   | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.<br>Default unit: vp|
3095| dirtyY      | number \| string<sup>10+</sup> | Yes   | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.<br>Default unit: vp|
3096| dirtyWidth  | number \| string<sup>10+</sup> | Yes   | Width of the rectangular area to crop the source image.<br>Default unit: vp|
3097| dirtyHeight | number \| string<sup>10+</sup> | Yes   | Height of the rectangular area to crop the source image.<br>Default unit: vp|
3098
3099**Example**
3100
3101  ```ts
3102  // xxx.ets
3103  @Entry
3104  @Component
3105  struct PutImageData {
3106    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3107    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3108
3109    build() {
3110      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3111        Canvas(this.context)
3112          .width('100%')
3113          .height('100%')
3114          .backgroundColor('#ffff00')
3115          .onReady(() => {
3116            let imageDataNum = this.context.createImageData(100, 100)
3117            let imageData = this.context.createImageData(imageDataNum)
3118            for (let i = 0; i < imageData.data.length; i += 4) {
3119              imageData.data[i + 0] = 255
3120              imageData.data[i + 1] = 0
3121              imageData.data[i + 2] = 255
3122              imageData.data[i + 3] = 255
3123            }
3124            this.context.putImageData(imageData, 10, 10)
3125            this.context.putImageData(imageData, 150, 10, 0, 0, 50, 50)
3126          })
3127      }
3128      .width('100%')
3129      .height('100%')
3130    }
3131  }
3132  ```
3133
3134  ![en-us_image_0000001238952387](figures/en-us_image_0000001238952387.png)
3135
3136
3137### setLineDash
3138
3139setLineDash(segments: number[]): void
3140
3141Sets the dash line style.
3142
3143**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3144
3145**Atomic service API**: This API can be used in atomic services since API version 11.
3146
3147**System capability**: SystemCapability.ArkUI.ArkUI.Full
3148
3149**Parameters**
3150
3151| Name     | Type     | Mandatory | Description|
3152| -------- | -------- | ------- | ------------ |
3153| segments | number[] | Yes| An array of numbers that specify distances to alternately draw a line and a gap.<br>Default unit: vp|
3154
3155**Example**
3156
3157  ```ts
3158  // xxx.ets
3159  @Entry
3160  @Component
3161  struct SetLineDash {
3162    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3163    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3164
3165    build() {
3166      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3167        Canvas(this.context)
3168          .width('100%')
3169          .height('100%')
3170          .backgroundColor('#ffff00')
3171          .onReady(() =>{
3172            this.context.arc(100, 75, 50, 0, 6.28)
3173            this.context.setLineDash([10,20])
3174            this.context.stroke()
3175          })
3176      }
3177      .width('100%')
3178      .height('100%')
3179    }
3180  }
3181  ```
3182
3183  ![en-us_image_000000127777771](figures/en-us_image_000000127777771.png)
3184
3185
3186### getLineDash
3187
3188getLineDash(): number[]
3189
3190Obtains the dash line style.
3191
3192**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3193
3194**Atomic service API**: This API can be used in atomic services since API version 11.
3195
3196**System capability**: SystemCapability.ArkUI.ArkUI.Full
3197
3198**Return value**
3199
3200| Type      | Description                      |
3201| -------- | ------------------------ |
3202| number[] | Interval of alternate line segments and the length of spacing.<br>Default unit: vp|
3203
3204
3205**Example**
3206
3207  ```ts
3208  // xxx.ets
3209  @Entry
3210  @Component
3211  struct CanvasGetLineDash {
3212    @State message: string = 'Hello World'
3213    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3214    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3215
3216    build() {
3217      Row() {
3218        Column() {
3219          Text(this.message)
3220            .fontSize(50)
3221            .fontWeight(FontWeight.Bold)
3222            .onClick(()=>{
3223              console.error('before getlinedash clicked')
3224              let res = this.context.getLineDash()
3225              console.error(JSON.stringify(res))
3226            })
3227          Canvas(this.context)
3228            .width('100%')
3229            .height('100%')
3230            .backgroundColor('#ffff00')
3231            .onReady(() => {
3232              this.context.arc(100, 75, 50, 0, 6.28)
3233              this.context.setLineDash([10,20])
3234              this.context.stroke()
3235            })
3236        }
3237        .width('100%')
3238      }
3239      .height('100%')
3240    }
3241  }
3242  ```
3243![en-us_image_000000127777778](figures/en-us_image_000000127777778.png)
3244
3245
3246### transferFromImageBitmap
3247
3248transferFromImageBitmap(bitmap: ImageBitmap): void
3249
3250Displays the specified **ImageBitmap** object.
3251
3252**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3253
3254**Atomic service API**: This API can be used in atomic services since API version 11.
3255
3256**System capability**: SystemCapability.ArkUI.ArkUI.Full
3257
3258**Parameters**
3259
3260| Name| Type | Mandatory| Description |
3261| ------ | ----------------------- | ----------------- | ------------------ |
3262| bitmap | [ImageBitmap](ts-components-canvas-imagebitmap.md)  | Yes| **ImageBitmap** object to display.|
3263
3264**Example**
3265
3266  ```ts
3267  // xxx.ets
3268  @Entry
3269  @Component
3270  struct TransferFromImageBitmap {
3271    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3272    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3273    private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
3274
3275    build() {
3276      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3277        Canvas(this.context)
3278          .width('100%')
3279          .height('100%')
3280          .backgroundColor('rgb(213,213,213)')
3281          .onReady(() =>{
3282            let imageData = this.offContext.createImageData(100, 100)
3283            for (let i = 0; i < imageData.data.length; i += 4) {
3284              imageData.data[i + 0] = 255
3285              imageData.data[i + 1] = 0
3286              imageData.data[i + 2] = 60
3287              imageData.data[i + 3] = 80
3288            }
3289            this.offContext.putImageData(imageData, 10, 10)
3290            let image = this.offContext.transferToImageBitmap()
3291            this.context.transferFromImageBitmap(image)
3292          })
3293      }
3294      .width('100%')
3295      .height('100%')
3296    }
3297  }
3298  ```
3299  ![transferFromImageBitmap](figures/transferFromImageBitmap.jpg)
3300
3301
3302### toDataURL
3303
3304toDataURL(type?: string, quality?: any): string
3305
3306Creates a data URL that contains a representation of an image. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it.
3307
3308**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3309
3310**Atomic service API**: This API can be used in atomic services since API version 11.
3311
3312**System capability**: SystemCapability.ArkUI.ArkUI.Full
3313
3314**Parameters**
3315
3316| Name    | Type  | Mandatory | Description |
3317| ------- | ------ | ---- | ---------------------------------------- |
3318| type    | string | No | Image format.<br>The options are as follows: **"image/png"**, **"image/jpeg"**, **"image/webp"**.<br>Default value: **"image/png"**           |
3319| quality | any | No | Image quality, which ranges from 0 to 1, when the image format is **image/jpeg** or **image/webp**. If the set value is beyond the value range, the default value **0.92** is used.<br>Default value: **0.92**|
3320
3321**Return value**
3322
3323| Type    | Description       |
3324| ------ | --------- |
3325| string | Image URL.|
3326
3327**Example**
3328
3329  ```ts
3330  // xxx.ets
3331  @Entry
3332  @Component
3333  struct CanvasExample {
3334    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3335    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3336    @State toDataURL: string = ""
3337
3338    build() {
3339      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3340        Canvas(this.context)
3341          .width(100)
3342          .height(100)
3343          .onReady(() =>{
3344            this.context.fillStyle = "#00ff00"
3345            this.context.fillRect(0,0,100,100)
3346            this.toDataURL = this.context.toDataURL("image/png", 0.92)
3347          })
3348        Text(this.toDataURL)
3349      }
3350      .width('100%')
3351      .height('100%')
3352      .backgroundColor('#ffff00')
3353    }
3354  }
3355  ```
3356  ![en-us_image_0000001238952387](figures/en-us_image_0000001194192441.png)
3357
3358
3359### restore
3360
3361restore(): void
3362
3363Restores the saved drawing context.
3364
3365> **NOTE**
3366>
3367> When the number of calls to **restore()** does not exceed the number of calls to **save()**, this API pops the saved drawing state from the stack and restores the properties, clipping path, and transformation matrix of the **CanvasRenderingContext2D** object.<br>
3368> If the number of calls to **restore()** exceeds the number of calls to **save()**, this API does nothing.<br>
3369> If there is no saved state, this API does nothing.
3370
3371**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3372
3373**Atomic service API**: This API can be used in atomic services since API version 11.
3374
3375**System capability**: SystemCapability.ArkUI.ArkUI.Full
3376
3377**Example**
3378
3379  ```ts
3380  // xxx.ets
3381  @Entry
3382  @Component
3383  struct CanvasExample {
3384    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3385    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3386
3387    build() {
3388      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3389        Canvas(this.context)
3390          .width('100%')
3391          .height('100%')
3392          .backgroundColor('#ffff00')
3393          .onReady(() =>{
3394            this.context.save() // save the default state
3395            this.context.fillStyle = "#00ff00"
3396            this.context.fillRect(20, 20, 100, 100)
3397            this.context.restore() // restore to the default state
3398            this.context.fillRect(150, 75, 100, 100)
3399          })
3400      }
3401      .width('100%')
3402      .height('100%')
3403    }
3404  }
3405  ```
3406  ![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
3407
3408
3409### save
3410
3411save(): void
3412
3413Saves all states of the canvas in the stack. This API is usually called when the drawing state needs to be saved.
3414
3415**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3416
3417**Atomic service API**: This API can be used in atomic services since API version 11.
3418
3419**System capability**: SystemCapability.ArkUI.ArkUI.Full
3420
3421**Example**
3422
3423  ```ts
3424  // xxx.ets
3425  @Entry
3426  @Component
3427  struct CanvasExample {
3428    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3429    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3430
3431    build() {
3432      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3433        Canvas(this.context)
3434          .width('100%')
3435          .height('100%')
3436          .backgroundColor('#ffff00')
3437          .onReady(() =>{
3438            this.context.save() // save the default state
3439            this.context.fillStyle = "#00ff00"
3440            this.context.fillRect(20, 20, 100, 100)
3441            this.context.restore() // restore to the default state
3442            this.context.fillRect(150, 75, 100, 100)
3443          })
3444      }
3445      .width('100%')
3446      .height('100%')
3447    }
3448  }
3449  ```
3450  ![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
3451
3452
3453### createLinearGradient
3454
3455createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient
3456
3457Creates a linear gradient.
3458
3459**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3460
3461**Atomic service API**: This API can be used in atomic services since API version 11.
3462
3463**System capability**: SystemCapability.ArkUI.ArkUI.Full
3464
3465**Parameters**
3466
3467| Name  | Type    | Mandatory| Description  |
3468| ---- | ------ | ---- | -------- |
3469| x0   | number | Yes | X coordinate of the start point.<br>Default unit: vp|
3470| y0   | number | Yes | Y coordinate of the start point.<br>Default unit: vp|
3471| x1   | number | Yes | X coordinate of the end point.<br>Default unit: vp|
3472| y1   | number | Yes | Y coordinate of the end point.<br>Default unit: vp|
3473
3474**Return value**
3475
3476| Type    | Description       |
3477| ------ | --------- |
3478| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas.|
3479
3480**Example**
3481
3482  ```ts
3483  // xxx.ets
3484  @Entry
3485  @Component
3486  struct CreateLinearGradient {
3487    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3488    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3489
3490    build() {
3491      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3492        Canvas(this.context)
3493          .width('100%')
3494          .height('100%')
3495          .backgroundColor('#ffff00')
3496          .onReady(() =>{
3497            let grad = this.context.createLinearGradient(50,0, 300,100)
3498            grad.addColorStop(0.0, '#ff0000')
3499            grad.addColorStop(0.5, '#ffffff')
3500            grad.addColorStop(1.0, '#00ff00')
3501            this.context.fillStyle = grad
3502            this.context.fillRect(0, 0, 400, 400)
3503          })
3504      }
3505      .width('100%')
3506      .height('100%')
3507    }
3508  }
3509  ```
3510
3511  ![en-us_image_0000001194032516](figures/en-us_image_0000001194032516.jpeg)
3512
3513
3514### createRadialGradient
3515
3516createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient
3517
3518Creates a linear gradient.
3519
3520**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3521
3522**Atomic service API**: This API can be used in atomic services since API version 11.
3523
3524**System capability**: SystemCapability.ArkUI.ArkUI.Full
3525
3526**Parameters**
3527
3528| Name  | Type    | Mandatory  | Description   |
3529| ---- | ------ | ---- | ----------------- |
3530| x0   | number | Yes | X coordinate of the center of the start circle.<br>Default unit: vp|
3531| y0   | number | Yes | Y coordinate of the center of the start circle.<br>Default unit: vp|
3532| r0   | number | Yes | Radius of the start circle, which must be a non-negative finite number.<br>Default unit: vp|
3533| x1   | number | Yes | X coordinate of the center of the end circle.<br>Default unit: vp|
3534| y1   | number | Yes | Y coordinate of the center of the end circle.<br>Default unit: vp|
3535| r1   | number | Yes | Radius of the end circle, which must be a non-negative finite number.<br>Default unit: vp|
3536
3537**Return value**
3538
3539| Type    | Description       |
3540| ------ | --------- |
3541| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas.|
3542
3543**Example**
3544
3545  ```ts
3546  // xxx.ets
3547  @Entry
3548  @Component
3549  struct CreateRadialGradient {
3550    private settings: RenderingContextSettings = new RenderingContextSettings(true)
3551    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3552
3553    build() {
3554      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3555        Canvas(this.context)
3556          .width('100%')
3557          .height('100%')
3558          .backgroundColor('#ffff00')
3559          .onReady(() =>{
3560            let grad = this.context.createRadialGradient(200,200,50, 200,200,200)
3561            grad.addColorStop(0.0, '#ff0000')
3562            grad.addColorStop(0.5, '#ffffff')
3563            grad.addColorStop(1.0, '#00ff00')
3564            this.context.fillStyle = grad
3565            this.context.fillRect(0, 0, 440, 440)
3566          })
3567      }
3568      .width('100%')
3569      .height('100%')
3570    }
3571  }
3572  ```
3573
3574  ![en-us_image_0000001238952407](figures/en-us_image_0000001238952407.jpeg)
3575
3576### createConicGradient<sup>10+</sup>
3577
3578createConicGradient(startAngle: number, x: number, y: number): CanvasGradient
3579
3580Creates a conic gradient.
3581
3582**Atomic service API**: This API can be used in atomic services since API version 11.
3583
3584**System capability**: SystemCapability.ArkUI.ArkUI.Full
3585
3586**Parameters**
3587
3588| Name  | Type    | Mandatory| Description |
3589| ---------- | ------ | ---- | ----------------------------------- |
3590| startAngle | number | Yes   | Angle at which the gradient starts. The angle measurement starts horizontally from the right side of the center and moves clockwise.<br>Unit: radian|
3591| x          | number | Yes   | X coordinate of the center of the conic gradient,<br>Default unit: vp|
3592| y          | number | Yes   | Y coordinate of the center of the conic gradient,<br>Default unit: vp|
3593
3594**Return value**
3595
3596| Type    | Description       |
3597| ------ | --------- |
3598| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas.|
3599
3600**Example**
3601
3602```ts
3603// xxx.ets
3604@Entry
3605@Component
3606struct CanvasExample {
3607  private settings: RenderingContextSettings = new RenderingContextSettings(true)
3608  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3609
3610  build() {
3611    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3612      Canvas(this.context)
3613        .width('100%')
3614        .height('100%')
3615        .backgroundColor('#ffffff')
3616        .onReady(() => {
3617          let grad = this.context.createConicGradient(0, 50, 80)
3618          grad.addColorStop(0.0, '#ff0000')
3619          grad.addColorStop(0.5, '#ffffff')
3620          grad.addColorStop(1.0, '#00ff00')
3621          this.context.fillStyle = grad
3622          this.context.fillRect(0, 30, 100, 100)
3623        })
3624    }
3625    .width('100%')
3626    .height('100%')
3627  }
3628}
3629```
3630
3631  ![en-us_image_0000001239032419](figures/en-us_image_0000001239032420.png)
3632
3633### on('onAttach')<sup>13+</sup>
3634
3635on(type: 'onAttach', callback: () => void): void
3636
3637Subscribes to the event when a **CanvasRenderingContext2D** object is bound to a **Canvas** component.
3638
3639**Atomic service API**: This API can be used in atomic services since API version 13.
3640
3641**System capability**: SystemCapability.ArkUI.ArkUI.Full
3642
3643**Parameters**
3644
3645| Name| Type     | Mandatory| Description                                                                  |
3646| ------ | --------- | ---- | ---------------------------------------------------------------------- |
3647| type   | string | Yes  | Event type, which is **'onAttach'** in this case.|
3648| callback   | () => void | Yes  | Callback triggered when the **CanvasRenderingContext2D** object is bound to the **Canvas** component.|
3649
3650> **NOTE**
3651>
3652> A **CanvasRenderingContext2D** object can only be bound to one **Canvas** component at a time.<br>
3653> When a **CanvasRenderingContext2D** object is bound to a **Canvas** component, the **onAttach** callback is triggered, indicating that the [canvas](#canvas13) object is accessible.<br>
3654> Avoid performing drawing operations in the **onAttach** callback. Make sure the **Canvas** component has completed its **[onReady](ts-components-canvas-canvas.md#events)** event before performing any drawing.<br>
3655> The **onAttach** callback is triggered when:<br>
3656> 1. A **Canvas** component is created and bound to a **CanvasRenderingContext2D** object.<br>
3657> 2. A **CanvasRenderingContext2D** object is bound to a new **Canvas** component.<br>
3658
3659
3660### on('onDetach')<sup>13+</sup>
3661
3662on(type: 'onDetach', callback: () => void): void
3663
3664Subscribes to the event when a **CanvasRenderingContext2D** object is unbound from a **Canvas** component.
3665
3666**Atomic service API**: This API can be used in atomic services since API version 13.
3667
3668**System capability**: SystemCapability.ArkUI.ArkUI.Full
3669
3670**Parameters**
3671
3672| Name| Type     | Mandatory| Description                                                                  |
3673| ------ | --------- | ---- | ---------------------------------------------------------------------- |
3674| type   | string | Yes  | Event type, which is **'onDetach'** in this case.|
3675| callback   | () => void | Yes  | Callback triggered when the **CanvasRenderingContext2D** object is unbound from the **Canvas** component.|
3676
3677> **NOTE**
3678>
3679> When a **CanvasRenderingContext2D** object is unbound from a **Canvas** component, the **onDetach** callback is triggered. In this case, cease any drawing operations.<br>
3680> The **onDetach** callback is triggered when:<br>
3681> 1. A **Canvas** component is destroyed and unbound from a **CanvasRenderingContext2D** object.<br>
3682> 2. A **CanvasRenderingContext2D** object is bound to a different** Canvas** component, causing the existing binding to be released.<br>
3683
3684### off('onAttach')<sup>13+</sup>
3685
3686off(type: 'onAttach', callback?: () => void): void
3687
3688Unsubscribes from the event when a **CanvasRenderingContext2D** object is bound to a **Canvas** component.
3689
3690**Atomic service API**: This API can be used in atomic services since API version 13.
3691
3692**System capability**: SystemCapability.ArkUI.ArkUI.Full
3693
3694**Parameters**
3695
3696| Name| Type     | Mandatory| Description                                                                  |
3697| ------ | --------- | ---- | ---------------------------------------------------------------------- |
3698| type   | string | Yes  | Event type, which is **'onAttach'** in this case.|
3699| callback   | () => void | No  | Callback to unregister.<br>If this parameter is not specified, this API unregisters all callbacks for the **'onAttach'** event.|
3700
3701### off('onDetach')<sup>13+</sup>
3702
3703off(type: 'onDetach', callback?: () => void): void
3704
3705Unsubscribes from the event when a **CanvasRenderingContext2D** object is unbound from a **Canvas** component.
3706
3707**Atomic service API**: This API can be used in atomic services since API version 13.
3708
3709**System capability**: SystemCapability.ArkUI.ArkUI.Full
3710
3711**Parameters**
3712
3713| Name| Type     | Mandatory| Description                                                                  |
3714| ------ | --------- | ---- | ---------------------------------------------------------------------- |
3715| type   | string | Yes  | Event type, which is **'onDetach'** in this case.|
3716| callback   | () => void | No  | Callback to unregister.<br>If this parameter is not specified, this API unregisters all callbacks for the **'onDetach'** event.|
3717
3718**Example**
3719
3720```ts
3721import { FrameNode } from '@kit.ArkUI'
3722// xxx.ets
3723@Entry
3724@Component
3725struct AttachDetachExample {
3726  private settings: RenderingContextSettings = new RenderingContextSettings(true)
3727  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3728  private scroller: Scroller = new Scroller()
3729  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
3730  private node: FrameNode | null = null
3731  private attachCallback: Callback<void> = this.attachFunc.bind(this)
3732  private detachCallback: Callback<void> = this.detachFunc.bind(this)
3733
3734  attachFunc(): void {
3735    console.info('CanvasRenderingContext2D attached to the canvas frame node.')
3736    this.node = this.context.canvas
3737  }
3738  detachFunc(): void {
3739    console.info('CanvasRenderingContext2D detach from the canvas frame node.')
3740    this.node = null
3741  }
3742  aboutToAppear(): void {
3743    this.context.on('onAttach', this.attachCallback)
3744    this.context.on('onDetach', this.detachCallback)
3745  }
3746  aboutToDisappear(): void {
3747    this.context.off('onAttach')
3748    this.context.off('onDetach')
3749  }
3750
3751  build() {
3752    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3753      Scroll(this.scroller) {
3754        Flex({ direction: FlexDirection.Column}) {
3755          ForEach(this.arr, (item: number) => {
3756            Row() {
3757              if (item == 3) {
3758                Canvas(this.context)
3759                  .width('100%')
3760                  .height(150)
3761                  .backgroundColor('rgb(213,213,213)')
3762                  .onReady(() => {
3763                    this.context.font = '30vp sans-serif'
3764                    this.node?.commonEvent.setOnVisibleAreaApproximateChange(
3765                      { ratios: [0, 1], expectedUpdateInterval: 10},
3766                      (isVisible: boolean, currentRatio: number) => {
3767                        if (!isVisible && currentRatio <= 0.0) {
3768                          console.info('Canvas is completely invisible.')
3769                        }
3770                        if (isVisible && currentRatio >= 1.0) {
3771                          console.info('Canvas is fully visible.')
3772                        }
3773                      }
3774                    )
3775                  })
3776              } else {
3777                Text(item.toString())
3778                  .width('100%')
3779                  .height(150)
3780                  .backgroundColor('rgb(39,135,217)')
3781                  .borderRadius(15)
3782                  .fontSize(16)
3783                  .textAlign(TextAlign.Center)
3784                  .margin({ top: 5 })
3785              }
3786            }
3787          }, (item: number) => item.toString())
3788        }
3789      }
3790      .width('90%')
3791      .scrollBar(BarState.Off)
3792      .scrollable(ScrollDirection.Vertical)
3793    }
3794    .width('100%')
3795    .height('100%')
3796  }
3797}
3798```
3799
3800![on_off_1](figures/on_off_cut.gif)
3801
3802### startImageAnalyzer<sup>12+</sup>
3803
3804startImageAnalyzer(config: ImageAnalyzerConfig): Promise\<void>
3805
3806Starts AI image analysis in the given settings. Before calling this API, make sure the AI image analyzer is [enabled](ts-components-canvas-canvas.md#enableanalyzer12).<br>Because the image frame used for analysis is the one captured when this API is called, pay attention to the invoking time of this API.<br>If this method is repeatedly called before the execution is complete, an error callback is triggered. For the sample code, see the code for **stopImageAnalyzer**.
3807
3808> **NOTE**
3809>
3810> The type of the AI analyzer cannot be dynamically modified.
3811> When image changes are detected, the analysis result is automatically destroyed. You can call this API again to start analysis.
3812> This API depends on device capabilities. If it is called on an incompatible device, an error code is returned.
3813
3814**Atomic service API**: This API can be used in atomic services since API version 12.
3815
3816**System capability**: SystemCapability.ArkUI.ArkUI.Full
3817
3818**Parameters**
3819
3820| Name| Type     | Mandatory| Description                                                                  |
3821| ------ | --------- | ---- | ---------------------------------------------------------------------- |
3822| config   | [ImageAnalyzerConfig](ts-image-common.md#imageanalyzerconfig) | Yes  | Settings of the AI analyzer.|
3823
3824**Return value**
3825
3826| Type             | Description                                |
3827| ----------------- | ------------------------------------ |
3828| Promise\<void>  | Promise used to return the result.|
3829
3830**Error codes**
3831
3832For details about the error codes, see [AI Analysis Error Codes](../errorcode-image-analyzer.md).
3833
3834| ID| Error Message                                     |
3835| -------- | -------------------------------------------- |
3836| 110001 | AI analysis is unsupported.               |
3837| 110002 | AI analysis is ongoing.  |
3838
3839### stopImageAnalyzer<sup>12+</sup>
3840
3841stopImageAnalyzer(): void
3842
3843Stops AI image analysis. The content displayed by the AI analyzer will be destroyed.
3844
3845> **NOTE**
3846>
3847> If this API is called when the **startImageAnalyzer** API has not yet returned any result, an error is reported.
3848> This feature depends on device capabilities.
3849
3850**Atomic service API**: This API can be used in atomic services since API version 12.
3851
3852**System capability**: SystemCapability.ArkUI.ArkUI.Full
3853
3854**Example**
3855
3856```ts
3857// xxx.ets
3858import { BusinessError } from '@kit.BasicServicesKit';
3859
3860@Entry
3861@Component
3862struct ImageAnalyzerExample {
3863  private settings: RenderingContextSettings = new RenderingContextSettings(true)
3864  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
3865  private config: ImageAnalyzerConfig = {
3866    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT]
3867  }
3868  private img = new ImageBitmap('page/common/test.jpg')
3869  private aiController: ImageAnalyzerController = new ImageAnalyzerController()
3870  private options: ImageAIOptions = {
3871    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
3872    aiController: this.aiController
3873  }
3874
3875  build() {
3876    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
3877      Button('start')
3878        .width(80)
3879        .height(80)
3880        .onClick(() => {
3881          this.context.startImageAnalyzer(this.config)
3882            .then(() => {
3883              console.log("analysis complete")
3884            })
3885            .catch((error: BusinessError) => {
3886              console.log("error code: " + error.code)
3887            })
3888        })
3889      Button('stop')
3890        .width(80)
3891        .height(80)
3892        .onClick(() => {
3893          this.context.stopImageAnalyzer()
3894        })
3895      Button('getTypes')
3896        .width(80)
3897        .height(80)
3898        .onClick(() => {
3899          this.aiController.getImageAnalyzerSupportTypes()
3900        })
3901      Canvas(this.context, this.options)
3902        .width(200)
3903        .height(200)
3904        .enableAnalyzer(true)
3905        .onReady(() => {
3906          this.context.drawImage(this.img, 0, 0, 200, 200)
3907        })
3908    }
3909    .width('100%')
3910    .height('100%')
3911  }
3912}
3913```
3914
3915## CanvasDirection
3916
3917**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3918
3919**Atomic service API**: This API can be used in atomic services since API version 11.
3920
3921**System capability**: SystemCapability.ArkUI.ArkUI.Full
3922
3923| Type     | Description                 |
3924| ------- | ------------------- |
3925| inherit | The text direction is inherited from the **Canvas** component.|
3926| ltr     | The text direction is from left to right.              |
3927| rtl     | The text direction is from right to left.              |
3928
3929## CanvasFillRule
3930
3931**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3932
3933**Atomic service API**: This API can be used in atomic services since API version 11.
3934
3935**System capability**: SystemCapability.ArkUI.ArkUI.Full
3936
3937| Type     | Description   |
3938| ------- | ----- |
3939| evenodd | The inside part of a shape is determined based on whether the counting result is an odd number or not.|
3940| nonzero | The inside part of a shape is determined based on whether the counting result is zero or not.|
3941
3942## CanvasLineCap
3943
3944**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3945
3946**Atomic service API**: This API can be used in atomic services since API version 11.
3947
3948**System capability**: SystemCapability.ArkUI.ArkUI.Full
3949
3950| Type     | Description                          |
3951| ------ | ----------------------------- |
3952| butt   | The ends of the line are squared off, and the line does not extend beyond its two endpoints.              |
3953| round  | The line is extended at the endpoints by a half circle whose diameter is equal to the line width.           |
3954| square | The line is extended at the endpoints by a rectangle whose width is equal to half the line width and height equal to the line width.|
3955
3956## CanvasLineJoin
3957
3958**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3959
3960**Atomic service API**: This API can be used in atomic services since API version 11.
3961
3962**System capability**: SystemCapability.ArkUI.ArkUI.Full
3963
3964| Type     | Description                                      |
3965| ----- | ---------------------------------------- |
3966| bevel | The intersection is a triangle. The rectangular corner of each line is independent.            |
3967| miter | The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.|
3968| round | The intersection is a sector, whose radius at the rounded corner is equal to the line width.             |
3969
3970## CanvasTextAlign
3971
3972**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3973
3974**Atomic service API**: This API can be used in atomic services since API version 11.
3975
3976**System capability**: SystemCapability.ArkUI.ArkUI.Full
3977
3978| Type     | Description          |
3979| ------ | ------------ |
3980| center | The text is center-aligned.     |
3981| start  | The text is aligned with the start bound.|
3982| end    | The text is aligned with the end bound.|
3983| left   | The text is left-aligned.      |
3984| right  | The text is right-aligned.      |
3985
3986## CanvasTextBaseline
3987
3988**Widget capability**: This API can be used in ArkTS widgets since API version 9.
3989
3990**Atomic service API**: This API can be used in atomic services since API version 11.
3991
3992**System capability**: SystemCapability.ArkUI.ArkUI.Full
3993
3994| Type     | Description                                      |
3995| ----------- | ---------------------------------------- |
3996| alphabetic  | The text baseline is the normal alphabetic baseline.                           |
3997| bottom      | The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.|
3998| hanging     | The text baseline is a hanging baseline over the text.                              |
3999| ideographic | The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.|
4000| middle      | The text baseline is in the middle of the text bounding box.                            |
4001| top         | The text baseline is on the top of the text bounding box.                            |
4002
4003## ImageSmoothingQuality
4004
4005**Widget capability**: This API can be used in ArkTS widgets since API version 9.
4006
4007**Atomic service API**: This API can be used in atomic services since API version 11.
4008
4009**System capability**: SystemCapability.ArkUI.ArkUI.Full
4010
4011| Type     | Description  |
4012| ------ | ---- |
4013| low    | Low quality. |
4014| medium | Medium quality. |
4015| high   | High quality. |
4016
4017## TextMetrics
4018
4019**Widget capability**: This API can be used in ArkTS widgets since API version 9.
4020
4021**Atomic service API**: This API can be used in atomic services since API version 11.
4022
4023**System capability**: SystemCapability.ArkUI.ArkUI.Full
4024
4025| Name| Type| Read Only| Optional| Description|
4026| ---------- | -------------- | ------ | ---------------- | ------------------------ |
4027| width                    | number | Yes| No| Width of the text. Read-only.|
4028| height                   | number | Yes| No| Height of the text. Read-only.|
4029| actualBoundingBoxAscent  | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the bounding rectangle used to render the text. Read-only.|
4030| actualBoundingBoxDescent | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the bounding rectangle used to render the text. Read-only.|
4031| actualBoundingBoxLeft    | number | Yes| No| Distance parallel to the baseline from the alignment point determined by the [CanvasRenderingContext2D.textAlign](#canvastextalign) attribute to the left side of the bounding rectangle of the text. Read-only.|
4032| actualBoundingBoxRight   | number | Yes| No| Distance parallel to the baseline from the alignment point determined by the [CanvasRenderingContext2D.textAlign](#canvastextalign) attribute to the right side of the bounding rectangle of the text. Read-only.|
4033| alphabeticBaseline       | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the alphabetic baseline of the line box. Read-only.|
4034| emHeightAscent           | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the em square in the line box. Read-only.|
4035| emHeightDescent          | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the em square in the line box. Read-only.|
4036| fontBoundingBoxAscent    | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the bounding rectangle of all the fonts used to render the text. Read-only.|
4037| fontBoundingBoxDescent   | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the bounding rectangle of all the fonts used to render the text. Read-only.|
4038| hangingBaseline          | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the alphabetic baseline of the line box. Read-only.|
4039| ideographicBaseline      | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the ideographic baseline of the line box. Read-only.|
4040