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