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