We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All
ReferencesApplication FrameworkArkUIArkTS ComponentsCanvas DrawingCanvasRenderingContext2D

CanvasRenderingContext2D

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

After the CanvasRenderingContext2D object is bound to the Canvas component, you can draw shapes, texts, and images on the Canvas component.

NOTE
  • This API is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.

  • It is recommended that the CanvasRenderingContext2D object and the Canvas component be encapsulated into the same custom component, ensuring a one-to-one correspondence and consistent lifecycle between them.

  • When you call drawing APIs in this module, the commands are stored in the associated Canvas component's command queue. These commands are only executed when the current frame enters the rendering phase and the associated Canvas component is visible. Therefore, when the Canvas component is invisible (for example, off-screen or hidden), avoid frequent drawing calls to prevent command queue buildup and excessive memory usage.

  • The following path-related APIs apply only to paths created within CanvasRenderingContext2D and do not affect paths defined in OffscreenCanvasRenderingContext2D or Path2D: beginPath, moveTo, lineTo, closePath, bezierCurveTo, quadraticCurveTo, arc, arcTo, ellipse, rect, and roundRect.

  • When the width or height of the Canvas component exceeds 8000 px, rendering via the CPU causes significant performance degradation.

Constructor

constructor

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

constructor(settings?: RenderingContextSettings)

Constructs a canvas object, which supports configuration of parameters for the CanvasRenderingContext2D object.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
settings RenderingContextSettings No

Settings of the CanvasRenderingContext2D object. For details, see RenderingContextSettings.

If the value is undefined or null, the default value of RenderingContextSettings is used.

constructor12+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

constructor(settings?: RenderingContextSettings, unit?: LengthMetricsUnit)

Creates a CanvasRenderingContext2D object, allowing for initial configuration of rendering parameters and unit mode.

Widget capability: This API can be used in ArkTS widgets since API version 12.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
settings RenderingContextSettings No

Settings of the CanvasRenderingContext2D object. For details, see RenderingContextSettings.

If the value is undefined or null, the default value of RenderingContextSettings is used.

unit LengthMetricsUnit No

Unit mode of the CanvasRenderingContext2D object. The value cannot be dynamically changed once set.

Invalid values undefined, NaN and Infinity are treated as the default value.

Default value: DEFAULT.

Example

The following example shows how to specify the unit mode during the creation of a CanvasRenderingContext2D object. The default unit mode is LengthMetricsUnit.DEFAULT, which corresponds to the default unit vp. Once set, this unit mode cannot be changed dynamically. For details, see LengthMetricsUnit.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { LengthMetricsUnit } from '@kit.ArkUI'
  3. @Entry
  4. @Component
  5. struct LengthMetricsUnitDemo {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  7. private contextPX: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings, LengthMetricsUnit.PX);
  8. private contextVP: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.contextPX)
  12. .width('100%')
  13. .height(150)
  14. .backgroundColor('#ffff00')
  15. .onReady(() => {
  16. this.contextPX.fillRect(10, 10, 100, 100)
  17. this.contextPX.clearRect(10, 10, 50, 50)
  18. })
  19. Canvas(this.contextVP)
  20. .width('100%')
  21. .height(150)
  22. .backgroundColor('#ffff00')
  23. .onReady(() => {
  24. this.contextVP.fillRect(10, 10, 100, 100)
  25. this.contextVP.clearRect(10, 10, 50, 50)
  26. })
  27. }
  28. .width('100%')
  29. .height('100%')
  30. }
  31. }

Attributes

NOTE

The string format of fillStyle, shadowColor, and strokeStyle is rgb(255, 255, 255), rgba(255, 255, 255, 1.0), or #FFFFFF.

fillStyle

Sets the fill color for rendering. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
string | number10+ | CanvasGradient | CanvasPattern No No

- When the type is string, this attribute indicates the color of the fill area. For details about the color format, see the description for the string type in ResourceColor.

- When the type is number, this attribute indicates the color of the fill area. Fully transparent colors are not supported. For details about the color format, see the description for the number type in ResourceColor.

- When the type is CanvasGradient, this attribute indicates a gradient object, which is created via the createLinearGradient API.

- When the type is CanvasPattern, this attribute indicates a pattern, which is created via the createPattern API.

Default value: '#000000' (black)

Invalid values do not take effect. The effect before the setting is retained.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct FillStyleExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.fillStyle = '#0000ff'
  15. this.context.fillRect(20, 20, 150, 100)
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

lineWidth

Sets the line width. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number No No

Default value: 1 (px)

Default unit: vp

The value does not support 0 or negative numbers. 0, negative numbers, and NaN are handled as the default value. The value Infinity is invalid and no drawing is performed.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct LineWidthExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.lineWidth = 5
  15. this.context.strokeRect(25, 25, 85, 105)
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

strokeStyle

Sets the stroke color. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
string | number10+ | CanvasGradient | CanvasPattern No No

- When the type is string, this attribute indicates the stroke color. For details about the color format, see the description for the string type in ResourceColor.

- When the type is number, this attribute indicates the stroke color. Fully transparent colors are not supported. For details about the color format, see the description for the number type in ResourceColor.

- When the type is CanvasGradient, this attribute indicates a gradient object, which is created via the createLinearGradient API.

- When the type is CanvasPattern, this attribute indicates a pattern, which is created via the createPattern API.

Default value: '#000000' (black)

Invalid values do not take effect. The effect before the setting is retained.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct StrokeStyleExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.lineWidth = 10
  15. this.context.strokeStyle = '#0000ff'
  16. this.context.strokeRect(25, 25, 155, 105)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

lineCap

Sets the line caps. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
CanvasLineCap No No Default value: 'butt'
Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct LineCapExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.lineWidth = 8
  15. this.context.beginPath()
  16. this.context.lineCap = 'round'
  17. this.context.moveTo(30, 50)
  18. this.context.lineTo(220, 50)
  19. this.context.stroke()
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

lineJoin

Sets the line join. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
CanvasLineJoin No No

Available values are as follows:

- 'round': The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.

- 'bevel': The shape used to join line segments is a triangle. The rectangular corner of each line is independent.

- '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.

Default value: 'miter'

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct LineJoinExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.beginPath()
  15. this.context.lineWidth = 8
  16. this.context.lineJoin = 'miter'
  17. this.context.moveTo(30, 30)
  18. this.context.lineTo(120, 60)
  19. this.context.lineTo(30, 110)
  20. this.context.stroke()
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

miterLimit

Sets the miter limit, which specifies the distance between the inner and outer angles at line joins. This attribute takes effect only when lineJoin is set to miter. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number No No

Default value: 10px

Unit: px

The value of miterLimit cannot be 0 or a negative number. Values of 0, negative numbers, and NaN are handled with the default value. Infinity will cause an exception on the miterLimit attribute.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct MiterLimit {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.lineWidth = 8
  15. this.context.lineJoin = 'miter'
  16. this.context.miterLimit = 3
  17. this.context.moveTo(30, 30)
  18. this.context.lineTo(60, 35)
  19. this.context.lineTo(30, 37)
  20. this.context.stroke()
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

font

Sets the text font. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Syntax: ctx.font = 'font-style font-weight font-size font-family'

- (Optional) font-style: font style. Available values are normal and italic.

- (Optional) font-weight: font weight. Available values are as follows: normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900.

- (Optional) font-size: font size and line height. The unit can be px or vp and must be specified.

- (Optional) font-family: font family. Available values are sans-serif, serif, and monospace.

Starting from API version 20, this API is used to set registered custom fonts (the DevEco Studio Previewer does not support custom fonts). You can register a custom font in either of the following ways:

Register a custom font by calling the asynchronous API this.uiContext.getFont().registerFont of ArkUI. Immediate rendering after calling this API may result in the custom font not taking effect.

Directly call the fontCollection.loadFontSync API of the font engine to register the custom font. In this case, the fontCollection instance must be text.FontCollection.getGlobalInstance() because the component loads fonts from this instance by default. If you use another instance, the custom font may not take effect.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
string No No

Default value: 'normal normal 14px sans-serif'

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { text } from '@kit.ArkGraphics2D';
  3. @Entry
  4. @Component
  5. struct FontDemo {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Canvas(this.context)
  11. .width('100%')
  12. .height('100%')
  13. .backgroundColor('rgb(213,213,213)')
  14. .onReady(() => {
  15. // Normal font style, normal weight, font size of 30 px, and font family of sans-serif
  16. this.context.font = 'normal normal 30px sans-serif'
  17. this.context.fillText("Hello px", 20, 60)
  18. // Italic style, bold, font size of 30 vp, and font family of monospace
  19. this.context.font = 'italic bold 30vp monospace'
  20. this.context.fillText("Hello vp", 20, 100)
  21. // Load the custom font file HarmonyOS_Sans_Thin_Italic.ttf in the rawfile directory.
  22. let fontCollection = text.FontCollection.getGlobalInstance();
  23. fontCollection.loadFontSync('HarmonyOS_Sans_Thin_Italic', $rawfile("HarmonyOS_Sans_Thin_Italic.ttf"))
  24. // Bold, font size of 30 vp, and font family of HarmonyOS_Sans_Thin_Italic
  25. this.context.font = "bold 30vp HarmonyOS_Sans_Thin_Italic"
  26. this.context.fillText("Hello customFont", 20, 140)
  27. })
  28. }
  29. .width('100%')
  30. .height('100%')
  31. }
  32. }

textAlign

Sets the text alignment type. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
CanvasTextAlign No No

In the ltr layout mode, the value 'start' equals 'left'. In the rtl layout mode, the value 'start' equals 'right'.

Default value: 'left'

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.strokeStyle = 'rgb(39,135,217)'
  15. this.context.moveTo(140, 10)
  16. this.context.lineTo(140, 160)
  17. this.context.stroke()
  18. this.context.font = '50px sans-serif'
  19. this.context.textAlign = 'start'
  20. this.context.fillText('textAlign=start', 140, 60)
  21. this.context.textAlign = 'end'
  22. this.context.fillText('textAlign=end', 140, 80)
  23. this.context.textAlign = 'left'
  24. this.context.fillText('textAlign=left', 140, 100)
  25. this.context.textAlign = 'center'
  26. this.context.fillText('textAlign=center', 140, 120)
  27. this.context.textAlign = 'right'
  28. this.context.fillText('textAlign=right', 140, 140)
  29. })
  30. }
  31. .width('100%')
  32. .height('100%')
  33. }
  34. }

textBaseline

Sets the horizontal alignment baseline for text rendering. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
CanvasTextBaseline No No Default value: 'alphabetic'
Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct TextBaseline {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.strokeStyle = 'rgb(0,0,255)'
  15. this.context.moveTo(0, 120)
  16. this.context.lineTo(400, 120)
  17. this.context.stroke()
  18. this.context.font = '20px sans-serif'
  19. this.context.textBaseline = 'top'
  20. this.context.fillText('Top', 10, 120)
  21. this.context.textBaseline = 'bottom'
  22. this.context.fillText('Bottom', 55, 120)
  23. this.context.textBaseline = 'middle'
  24. this.context.fillText('Middle', 125, 120)
  25. this.context.textBaseline = 'alphabetic'
  26. this.context.fillText('Alphabetic', 195, 120)
  27. this.context.textBaseline = 'hanging'
  28. this.context.fillText('Hanging', 295, 120)
  29. })
  30. }
  31. .width('100%')
  32. .height('100%')
  33. }
  34. }

globalAlpha

Sets the opacity. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number No No

The value range is [0.0, 1.0]. 0.0 indicates completely transparent, and 1.0 indicates completely opaque. If the set value is less than 0.0, 0.0 will be used. If the set value is greater than 1.0, 1.0 will be used.

In versions earlier than API version 18, if **NaN **or Infinity is set, rendering APIs cannot be called for rendering after this API. In API version 18 and later versions, if NaN or Infinity is set, the current API does not take effect, and other rendering APIs with valid arguments can be called normally.

Default value: 1.0

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct GlobalAlpha {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.fillStyle = 'rgb(0,0,255)'
  15. this.context.fillRect(0, 0, 50, 50)
  16. this.context.globalAlpha = 0.4
  17. this.context.fillStyle = 'rgb(0,0,255)'
  18. this.context.fillRect(50, 50, 50, 50)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

lineDashOffset

Sets the dashed line offset of the canvas. The value is of the float type. This attribute takes effect only when setLineDash is set. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number No No

In versions earlier than API version 18, if NaN or Infinity is set, dashed lines are rendered as solid lines. In API version 18 and later versions, if NaN or Infinity is set, the current API does not take effect, and dashed lines are rendered normally.

Default value: 0.0

Default unit: vp

Invalid values NaN and Infinity are treated as the default value.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { AnimatorResult } from '@kit.ArkUI';
  3. @Entry
  4. @Component
  5. struct LineDashOffset {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. private animator: AnimatorResult | undefined = undefined;
  9. drawAntLine() { // Implement the ant line animation.
  10. this.animator = this.getUIContext().createAnimator({
  11. duration: 2000,
  12. easing: 'linear',
  13. delay: 0,
  14. fill: 'none',
  15. direction: 'normal',
  16. iterations: -1,
  17. begin: 0, // Start point of the animation interpolation.
  18. end: 1 // End point of the animation interpolation.
  19. });
  20. this.animator.onFrame = (value: number) => {
  21. this.context.reset();
  22. this.context.lineWidth = 2;
  23. this.context.setLineDash([10, 5]);
  24. this.context.lineDashOffset = 105 * value;
  25. this.context.strokeRect(10, 10, 100, 100);
  26. };
  27. this.animator.play();
  28. }
  29. aboutToDisappear() {
  30. this.animator?.finish();
  31. this.animator = undefined;
  32. }
  33. build() {
  34. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  35. Canvas(this.context)
  36. .width('100%')
  37. .height('100%')
  38. .backgroundColor('rgb(213,213,213)')
  39. .onReady(() => {
  40. this.drawAntLine();
  41. })
  42. }
  43. .width('100%')
  44. .height('100%')
  45. }
  46. }

globalCompositeOperation

Sets the composite operation. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
string No No

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'.

Default value: 'source-over'

Expand
Name Description
source-over Displays the new drawing above the existing drawing. Default value.
source-atop Displays the new drawing on the top of the existing drawing.
source-in Displays the new drawing inside the existing drawing.
source-out Displays part of the new drawing that is outside of the existing drawing.
destination-over Displays the existing drawing above the new drawing.
destination-atop Displays the existing drawing on the top of the new drawing.
destination-in Displays the existing drawing inside the new drawing.
destination-out Displays the existing drawing outside the new drawing.
lighter Displays both the new and existing drawing.
copy Displays the new drawing and neglects the existing drawing.
xor Combines the new drawing and existing drawing using the XOR operation.
Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct GlobalCompositeOperation {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. private context3: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  9. private context4: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  10. private context5: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  11. private context6: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  12. build() {
  13. Column() {
  14. Row() {
  15. // 1. source-over: The new shape is overlaid on the original shape. This attribute is used by default.
  16. Canvas(this.context1)
  17. .width('45%')
  18. .borderWidth(1)
  19. .margin(5)
  20. .onReady(() => {
  21. let ctx1 = this.context1;
  22. ctx1.fillStyle = 'rgb(39,135,217)';
  23. ctx1.fillRect(25, 25, 75, 75); // Original shape
  24. ctx1.globalCompositeOperation = 'source-over'; // Default value, which can be omitted.
  25. ctx1.fillStyle = 'rgb(23,169,141)';
  26. ctx1.fillRect(75, 75, 75, 75); // Display the new shape overlaid on the original shape.
  27. })
  28. // 2. destination-out: The existing shape is erased in the area of the new shape (This is the core logic of the eraser).
  29. Canvas(this.context2)
  30. .width('45%')
  31. .borderWidth(1)
  32. .margin(5)
  33. .onReady(() => {
  34. let ctx2 = this.context2;
  35. // Draw the background first.
  36. ctx2.fillStyle = 'rgb(39,135,217)';
  37. ctx2.fillRect(0, 0, ctx2.width, ctx2.height);
  38. // Set the composite operation to destination-out.
  39. ctx2.globalCompositeOperation = 'destination-out';
  40. // Draw a circle as the eraser.
  41. ctx2.beginPath();
  42. ctx2.arc(ctx2.width / 2, ctx2.height / 2, 60, 0, Math.PI * 2);
  43. ctx2.fill(); // Erase the background of the circle.
  44. })
  45. }
  46. .height('30%')
  47. Row() {
  48. // 3. source-in: Only the overlapping part between the new shape and the original shape is retained (clipping or masking).
  49. Canvas(this.context3)
  50. .width('45%')
  51. .borderWidth(1)
  52. .margin(5)
  53. .onReady(() => {
  54. let ctx3 = this.context3;
  55. // Draw the original shape (circle mask) first.
  56. ctx3.beginPath();
  57. ctx3.arc(ctx3.width / 2, ctx3.height / 2, 80, 0, Math.PI * 2);
  58. ctx3.fillStyle = '#fff';
  59. ctx3.fill();
  60. // Set the composite operation.
  61. ctx3.globalCompositeOperation = 'source-in';
  62. // Draw a new shape (gradient rectangle).
  63. const gradient = ctx3.createLinearGradient(0, 0, ctx3.width, ctx3.height);
  64. gradient.addColorStop(0, 'rgb(23,169,141)');
  65. gradient.addColorStop(1, 'rgb(39,135,217)');
  66. ctx3.fillStyle = gradient;
  67. ctx3.fillRect(0, 0, 200, 200); // Display gradient only in the circular area.
  68. })
  69. // 4. lighter: The new shape is overlaid on the original shape (the luminance is added, and the color filtering effect is achieved).
  70. Canvas(this.context4)
  71. .width('45%')
  72. .borderWidth(1)
  73. .margin(5)
  74. .onReady(() => {
  75. let ctx4 = this.context4;
  76. // Original shape (a semi-transparent red circle)
  77. ctx4.beginPath();
  78. ctx4.arc(70, 100, 50, 0, Math.PI * 2);
  79. ctx4.fillStyle = 'rgba(234, 67, 53, 0.7)';
  80. ctx4.fill();
  81. // Set the composite operation.
  82. ctx4.globalCompositeOperation = 'lighter';
  83. // New shape (a semi-transparent blue circle)
  84. ctx4.beginPath();
  85. ctx4.arc(110, 100, 50, 0, Math.PI * 2);
  86. ctx4.fillStyle = 'rgba(66, 133, 244, 0.7)';
  87. ctx4.fill(); // The overlapping area turns purple (luminance blending).
  88. })
  89. }
  90. .height('30%')
  91. Row() {
  92. // 5. destination-atop: retains the overlapping part of the original and new shapes and removes other parts.
  93. Canvas(this.context5)
  94. .width('45%')
  95. .borderWidth(1)
  96. .margin(5)
  97. .onReady(() => {
  98. let ctx5 = this.context5;
  99. // Original shape (a green rectangle)
  100. ctx5.fillStyle = 'rgb(23,169,141)';
  101. ctx5.fillRect(0, 0, ctx5.width, ctx5.height);
  102. // Set the composite operation.
  103. ctx5.globalCompositeOperation = 'destination-atop';
  104. // New shape (a small circle)
  105. ctx5.beginPath();
  106. ctx5.arc(ctx5.width / 2, ctx5.height / 2, 60, 0, Math.PI * 2);
  107. ctx5.fillStyle = '#000';
  108. ctx5.fill(); // Only the overlapping part of the rectangle and circle is retained.
  109. })
  110. // 6. Text mask (advanced usage of source-in)
  111. Canvas(this.context6)
  112. .width('45%')
  113. .borderWidth(1)
  114. .margin(5)
  115. .onReady(() => {
  116. let ctx6 = this.context6
  117. // Draw the text first (as a mask).
  118. ctx6.font = 'bold 40vp';
  119. ctx6.textAlign = 'center';
  120. ctx6.textBaseline = 'middle';
  121. ctx6.fillText('CANVAS', ctx6.width / 2, ctx6.height / 2);
  122. // Set the composite operation.
  123. ctx6.globalCompositeOperation = 'source-in';
  124. // Draw the gradient background (displayed only in the text area).
  125. let textGradient = ctx6.createLinearGradient(50, 0, 300, 100);
  126. textGradient.addColorStop(0.0, 'rgb(39,135,217)');
  127. textGradient.addColorStop(0.5, 'rgb(255,238,240)');
  128. textGradient.addColorStop(1.0, 'rgb(23,169,141)');
  129. ctx6.fillStyle = textGradient;
  130. ctx6.fillRect(0, 0, 200, 200); // The gradient fills only the text area.
  131. })
  132. }
  133. .height('30%')
  134. }
  135. .width('100%')
  136. .height('100%')
  137. }
  138. }

shadowBlur

Sets the blur level for drawing shadows. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number No No

Blur level. A larger value produces a greater blur effect. The value is of float type and must be greater than or equal to 0.

Default value: 0.0

Unit: px

The value of shadowBlur cannot be a negative number. A negative number, NaN, and Infinity are treated as the default value.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ShadowBlur {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.shadowBlur = 30
  15. this.context.shadowColor = 'rgb(0,0,0)'
  16. this.context.fillStyle = 'rgb(255,0,0)'
  17. this.context.fillRect(20, 20, 100, 80)
  18. })
  19. }
  20. .width('100%')
  21. .height('100%')
  22. }
  23. }

shadowColor

Sets the shadow color. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
string No No

For details about the color format, see the description for the string type in ResourceColor.

Default value: '#00000000' (transparent black)

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ShadowColor {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.shadowBlur = 30
  15. this.context.shadowColor = 'rgb(0,0,255)'
  16. this.context.fillStyle = 'rgb(255,0,0)'
  17. this.context.fillRect(30, 30, 100, 100)
  18. })
  19. }
  20. .width('100%')
  21. .height('100%')
  22. }
  23. }

shadowOffsetX

Sets the horizontal offset between the drawn shadow and the original object. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number No No

Default value: 0.0

Default unit: vp

Invalid values NaN and Infinity are treated as the default value.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ShadowOffsetX {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.shadowBlur = 10
  15. this.context.shadowOffsetX = 20
  16. this.context.shadowColor = 'rgb(0,0,0)'
  17. this.context.fillStyle = 'rgb(255,0,0)'
  18. this.context.fillRect(20, 20, 100, 80)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

shadowOffsetY

Sets the vertical offset between the drawn shadow and the original object. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number No No

Default value: 0.0

Default unit: vp

Invalid values NaN and Infinity are treated as the default value.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ShadowOffsetY {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.shadowBlur = 10
  15. this.context.shadowOffsetY = 20
  16. this.context.shadowColor = 'rgb(0,0,0)'
  17. this.context.fillStyle = 'rgb(255,0,0)'
  18. this.context.fillRect(30, 30, 100, 100)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

imageSmoothingEnabled

Indicates whether to apply image smoothing adjustments when drawing images. The value true means to enable smoothing, and false means to disable it. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
boolean No No Default value: true
NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ImageSmoothingEnabled {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. // Replace "common/images/icon.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/icon.jpg")
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#ffff00')
  15. .onReady(() => {
  16. this.context.imageSmoothingEnabled = false
  17. this.context.drawImage(this.img, 0, 0, 400, 200)
  18. })
  19. }
  20. .width('100%')
  21. .height('100%')
  22. }
  23. }

height

Component height.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number Yes No Default unit: vp
Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct HeightExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width(300)
  11. .height(300)
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. let h = this.context.height
  15. this.context.fillRect(0, 0, 300, h / 2)
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

width

Component width.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
number Yes No Default unit: vp
Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct WidthExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width(300)
  11. .height(300)
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. let w = this.context.width
  15. this.context.fillRect(0, 0, w / 2, 300)
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

canvas13+

FrameNode instance of the Canvas component associated with CanvasRenderingContext2D. It can be used to listen for the visibility status of the associated Canvas component.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
FrameNode Yes No Default value: null
Collapse
Word wrap
Dark theme
Copy code
  1. import { FrameNode } from '@kit.ArkUI'
  2. // xxx.ets
  3. @Entry
  4. @Component
  5. struct CanvasExample {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  8. private text: string = ''
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#ffff00')
  15. .onReady(() => {
  16. let node: FrameNode = this.context.canvas
  17. node?.commonEvent.setOnVisibleAreaApproximateChange(
  18. { ratios: [0, 1], expectedUpdateInterval: 10},
  19. (isVisible: boolean, currentRatio: number) => {
  20. if (!isVisible && currentRatio <= 0.0) {
  21. this.text = 'Canvas is completely invisible.'
  22. }
  23. if (isVisible && currentRatio >= 1.0) {
  24. this.text = 'Canvas is fully visible.'
  25. }
  26. this.context.reset()
  27. this.context.font = '30vp sans-serif'
  28. this.context.fillText(this.text, 50, 50)
  29. }
  30. )
  31. })
  32. }
  33. .width('100%')
  34. .height('100%')
  35. }
  36. }

imageSmoothingQuality

Sets the image smoothing quality when imageSmoothingEnabled is set to true. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
ImageSmoothingQuality No No Default value: "low"
NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ImageSmoothingQualityDemo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. // Replace "common/images/example.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#ffff00')
  15. .onReady(() => {
  16. let ctx = this.context
  17. ctx.imageSmoothingEnabled = true
  18. ctx.imageSmoothingQuality = 'high'
  19. ctx.drawImage(this.img, 0, 0, 400, 200)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

direction

Sets the text direction. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
CanvasDirection No No Default value: "inherit"
Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct DirectionDemo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. let ctx = this.context
  15. ctx.font = '48px serif';
  16. ctx.textAlign = 'start'
  17. ctx.fillText("Hi ltr!", 200, 50);
  18. ctx.direction = "rtl";
  19. ctx.fillText("Hi rtl!", 200, 100);
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

filter

Sets the filter for an image. Any number of filters can be combined. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
string No No

Available values are as follows:

- 'none': no filter effect.

- 'blur(<length>)': applies the Gaussian blur to the image. The value must be greater than or equal to 0. The unit can be px, vp, or rem. The default value is blur(0px).

- 'brightness([<number>|<percentage>])': applies a linear multiplier to the image to adjust its brightness. The value can be a number or a percentage, and must be greater than or equal to 0. The default value is brightness(1).

- 'contrast([<number>|<percentage>])': adjusts the contrast of the image. The value can be a number or a percentage, and must be greater than or equal to 0. The default value is contrast(1).

- 'grayscale([<number>|<percentage>])': converts the image to grayscale. The value can be a number or a percentage, and must be within the range of [0, 1]. The default value is grayscale(0).

- 'hue-rotate(<angle>)': applies hue rotation to the image. The value ranges from 0deg to 360deg. The default value is hue-rotate(0deg).

- 'invert([<number>|<percentage>])': inverts the input image. The value can be a number or a percentage, and must be within the range of [0, 1]. The default value is invert(0).

- 'opacity([<number>|<percentage>])': adjusts the opacity of the image. The value can be a number or a percentage, and must be within the range of [0, 1]. The default value is opacity(1).

- 'saturate([<number>|<percentage>])': adjusts the saturation of the image. The value can be a number or a percentage, and must be greater than or equal to 0. The default value is saturate(1).

- 'sepia([<number>|<percentage>])': converts the image to sepia. The value can be a number or a percentage, and must be within the range of [0, 1]. The default value is sepia(0).

NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct FilterDemo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. // Replace "common/images/example.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .onReady(() => {
  15. let ctx = this.context
  16. let img = this.img
  17. ctx.drawImage(img, 0, 0, 100, 100);
  18. ctx.filter = 'grayscale(50%)';
  19. ctx.drawImage(img, 100, 0, 100, 100);
  20. ctx.filter = 'sepia(60%)';
  21. ctx.drawImage(img, 200, 0, 100, 100);
  22. ctx.filter = 'saturate(30%)';
  23. ctx.drawImage(img, 0, 100, 100, 100);
  24. ctx.filter = 'hue-rotate(90deg)';
  25. ctx.drawImage(img, 100, 100, 100, 100);
  26. ctx.filter = 'invert(100%)';
  27. ctx.drawImage(img, 200, 100, 100, 100);
  28. ctx.filter = 'opacity(25%)';
  29. ctx.drawImage(img, 0, 200, 100, 100);
  30. ctx.filter = 'brightness(0.4)';
  31. ctx.drawImage(img, 100, 200, 100, 100);
  32. ctx.filter = 'contrast(200%)';
  33. ctx.drawImage(img, 200, 200, 100, 100);
  34. ctx.filter = 'blur(5px)';
  35. ctx.drawImage(img, 0, 300, 100, 100);
  36. // Applying multiple filters
  37. ctx.filter = 'opacity(50%) contrast(200%) grayscale(50%)';
  38. ctx.drawImage(img, 100, 300, 100, 100);
  39. })
  40. }
  41. .width('100%')
  42. .height('100%')
  43. }
  44. }

letterSpacing18+

Sets the letter spacing. This attribute is write-only. You can set its value through an assignment statement, but cannot obtain its current value through a read operation. If you attempt to read its current value, undefined will be returned.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
string | LengthMetrics No No

Spacing between characters.

When the LengthMetrics type is used:

The spacing is set according to the specified unit.

The FP, PERCENT, and LPX units are not supported and will be treated as invalid values.

Negative and fractional values are supported. When set to a fraction, the spacing is not rounded.

When the string type is used:

Percentage values are not supported and will be treated as invalid.

Negative and decimal values are supported. When set to a decimal value, the spacing is not rounded.

If no unit is specified (for example, letterSpacing = '10') and LengthMetricsUnit is not set, the default unit is vp.

If LengthMetricsUnit is set to px, the default unit is px.

If the value of letterSpacing is specified with a unit (for example, letterSpacing='10vp'), the letter spacing is set based on the specified unit.

Default value: 0 (Invalid values are treated as the default value.)

NOTE

The LengthMetrics type is recommended for better performance.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { LengthMetrics, LengthUnit } from '@kit.ArkUI'
  3. @Entry
  4. @Component
  5. struct letterSpacingDemo {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Canvas(this.context)
  11. .width('100%')
  12. .height('100%')
  13. .backgroundColor('rgb(213,213,213)')
  14. .onReady(() => {
  15. this.context.font = '30vp'
  16. this.context.letterSpacing = '10vp'
  17. this.context.fillText('hello world', 30, 50)
  18. this.context.letterSpacing = new LengthMetrics(10, LengthUnit.VP)
  19. this.context.fillText('hello world', 30, 100)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

antialias24+

Sets whether to enable anti-aliasing for drawing graphics and text. Setting this API overrides the anti-aliasing effect in RenderingContextSettings. If this API is not specified, the default value is undefined and the anti-aliasing effect in RenderingContextSettings is used.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 24.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Read Only Optional Description
boolean | undefined No No

Whether to enable anti-aliasing for drawing graphics and text.

true: Anti-aliasing is enabled. false: Anti-aliasing is disabled.

When the value is undefined, the anti-aliasing effect in RenderingContextSettings is used.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct AntialiasDemo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. let anti = this.context.antialias;
  15. console.info(`current antialias is ${anti}`);
  16. // Set antialias to false.
  17. this.context.antialias = false;
  18. this.context.strokeStyle = 'rgb(0,0,0)';
  19. this.context.lineWidth = 2;
  20. this.context.beginPath();
  21. this.context.arc(150, 150, 100, 0, Math.PI);
  22. this.context.stroke();
  23. this.context.font = 'normal bold 30vp monospace';
  24. this.context.fillText("Hello World", 20, 100);
  25. anti = this.context.antialias;
  26. console.info(`current antialias is ${anti}`);
  27. // Set antialias to true.
  28. this.context.antialias = true;
  29. this.context.beginPath();
  30. this.context.arc(150, 350, 100, 0, Math.PI);
  31. this.context.stroke();
  32. this.context.font = 'normal bold 30vp monospace';
  33. this.context.fillText("Hello World", 20, 300);
  34. anti = this.context.antialias;
  35. console.info(`current antialias is ${anti}`);
  36. })
  37. }
  38. .width('100%')
  39. .height('100%')
  40. }
  41. }

Methods

Calls the following methods on hidden pages will result in cache data. Therefore, avoid frequent canvas refreshes on hidden pages.

fillRect

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

fillRect(x: number, y: number, w: number, h: number): void

Fills a rectangle on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the rectangle's top-left corner.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

y number Yes

Y-coordinate of the rectangle's top-left corner.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

w number Yes

Width of the rectangle.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

h number Yes

Height of the rectangle.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct FillRect {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.fillRect(30, 30, 100, 100)
  15. })
  16. }
  17. .width('100%')
  18. .height('100%')
  19. }
  20. }

strokeRect

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

strokeRect(x: number, y: number, w: number, h: number): void

Draws an outlined rectangle on the canvas without filling its interior.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the rectangle's top-left corner.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

y number Yes

Y-coordinate of the rectangle's top-left corner.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

w number Yes

Width of the rectangle.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

h number Yes

Height of the rectangle.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct StrokeRect {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.strokeRect(30, 30, 200, 150)
  15. })
  16. }
  17. .width('100%')
  18. .height('100%')
  19. }
  20. }

clearRect

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

clearRect(x: number, y: number, w: number, h: number): void

Clears the content in a rectangle on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the rectangle's top-left corner.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

y number Yes

Y-coordinate of the rectangle's top-left corner.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

w number Yes

Width of the rectangle.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

h number Yes

Height of the rectangle.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ClearRect {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.fillStyle = 'rgb(0,0,255)'
  15. this.context.fillRect(20, 20, 200, 200)
  16. this.context.clearRect(30, 30, 150, 100)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

fillText

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

fillText(text: string, x: number, y: number, maxWidth?: number): void

Draws filled text on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
text string Yes

Text to draw.

undefined and null are treated as invalid values and no rendering will be performed.

x number Yes

X-coordinate of the start point for text rendering.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

y number Yes

Y-coordinate of the start point for text rendering.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

maxWidth number No

Maximum width allowed for the text.

null is treated as an invalid value and no rendering will be performed. undefined, NaN, or Infinity is treated as the default value.

Default value: no width restriction

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct FillText {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.font = '30px sans-serif'
  15. this.context.fillText("Hello World!", 20, 100)
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

strokeText

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

strokeText(text: string, x: number, y: number, maxWidth?: number): void

Draws stroked text on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
text string Yes

Text to draw.

undefined and null are treated as invalid values and no rendering will be performed.

x number Yes

X-coordinate of the start point for text rendering.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

y number Yes

Y-coordinate of the start point for text rendering.

undefined, null, NaN, and Infinity are treated as invalid values and no rendering will be performed.

Default unit: vp

maxWidth number No

Maximum width of the text.

null is treated as an invalid value and no rendering will be performed. undefined, NaN, or Infinity is treated as the default value.

Default unit: vp

Default value: no width restriction

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct StrokeText {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.font = '50vp sans-serif'
  15. this.context.strokeText("Hello World!", 20, 60)
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

measureText

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

measureText(text: string): TextMetrics

Returns a TextMetrics object used to obtain the width of specified text. Note that the width obtained may vary by device.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
text string Yes

Text to measure.

If the input value is undefined or null, the value is calculated based on "undefined" or "null".

Return value

Expand
Type Description
TextMetrics TextMetrics object.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct MeasureText {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.font = '50px sans-serif'
  15. this.context.fillText("Hello World!", 20, 100)
  16. this.context.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

stroke

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

stroke(): void

Strokes (outlines) this path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Stroke {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.moveTo(125, 25)
  15. this.context.lineTo(125, 105)
  16. this.context.lineTo(175, 105)
  17. this.context.lineTo(175, 25)
  18. this.context.strokeStyle = 'rgb(255,0,0)'
  19. this.context.stroke()
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

stroke

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

stroke(path: Path2D): void

Strokes (outlines) a specified path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
path Path2D Yes

Path2D path to draw.

undefined and null are treated as invalid values and no rendering will be performed.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Stroke {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. private path2Da: Path2D = new Path2D()
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Canvas(this.context)
  11. .width('100%')
  12. .height('100%')
  13. .backgroundColor('#ffff00')
  14. .onReady(() => {
  15. this.path2Da.moveTo(25, 25)
  16. this.path2Da.lineTo(25, 105)
  17. this.path2Da.lineTo(75, 105)
  18. this.path2Da.lineTo(75, 25)
  19. this.context.strokeStyle = 'rgb(0,0,255)'
  20. this.context.stroke(this.path2Da)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

beginPath

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

beginPath(): void

Creates a drawing path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct BeginPath {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.lineWidth = 6
  15. this.context.strokeStyle = 'rgb(39,135,217)'
  16. this.context.moveTo(15, 80)
  17. this.context.lineTo(280, 160)
  18. this.context.stroke()
  19. this.context.beginPath()
  20. this.context.lineTo(300, 240)
  21. this.context.lineTo(15, 240)
  22. this.context.stroke()
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

moveTo

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

moveTo(x: number, y: number): void

Moves a drawing path from the current position to a target position on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the target position.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Y-coordinate of the target position.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

NOTE

In versions earlier than API version 18, if the moveTo API is not called or invalid arguments are passed to it, the path starts from (0,0).

Starting from API version 18, if the moveTo API is not executed or invalid arguments are passed to it, the path will begin at the start point of the first valid call to lineTo, arcTo, bezierCurveTo, or quadraticCurveTo.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct MoveTo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.beginPath()
  15. this.context.moveTo(10, 10)
  16. this.context.lineTo(280, 160)
  17. this.context.stroke()
  18. })
  19. }
  20. .width('100%')
  21. .height('100%')
  22. }
  23. }

lineTo

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

lineTo(x: number, y: number): void

Connects the current point to a target position using a line.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the target position.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Y-coordinate of the target position.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct LineTo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.beginPath()
  15. this.context.moveTo(10, 10)
  16. this.context.lineTo(280, 160)
  17. this.context.stroke()
  18. })
  19. }
  20. .width('100%')
  21. .height('100%')
  22. }
  23. }

closePath

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

closePath(): void

Draws a closed path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ClosePath {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.beginPath()
  15. this.context.moveTo(30, 30)
  16. this.context.lineTo(110, 30)
  17. this.context.lineTo(70, 90)
  18. this.context.closePath()
  19. this.context.stroke()
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

createPattern

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | null

Creates a pattern for image filling based on a specified source image and repetition mode.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
image ImageBitmap Yes

Source image. For details, see ImageBitmap.

undefined and null are treated as invalid values.

repetition string | null Yes

Repetition mode.

'repeat': The image is repeated along both the x-axis and y-axis.

'repeat-x': The image is repeated along the x-axis.

'repeat-y': The image is repeated along the y-axis.

'no-repeat': The image is not repeated.

'clamp': Coordinates outside the original bounds are clamped to the edge of the image.

'mirror': The image is mirrored with each repetition along the x-axis and y-axis.

undefined and null are treated as invalid values.

Return value

Expand
Type Description
CanvasPattern | null Pattern for image filling based on a specified source image and repetition mode.

Example

NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CreatePattern {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. // Replace "common/images/icon.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/icon.jpg")
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#ffff00')
  15. .onReady(() => {
  16. let pattern = this.context.createPattern(this.img, 'repeat')
  17. if (pattern) {
  18. this.context.fillStyle = pattern
  19. }
  20. this.context.fillRect(0, 0, 200, 200)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

bezierCurveTo

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void

Creates a path for a cubic Bezier curve.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
cp1x number Yes

X-coordinate of the first parameter of the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

cp1y number Yes

Y-coordinate of the first parameter of the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

cp2x number Yes

X-coordinate of the second parameter of the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

cp2y number Yes

Y-coordinate of the second parameter of the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

x number Yes

X-coordinate of the end point on the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Y-coordinate of the end point on the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { Point } from '@kit.TestKit';
  3. @Entry
  4. @Component
  5. struct BezierCurveTo {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. private start: Point = { x: 50, y: 50 };
  9. private end: Point = { x: 250, y: 100 };
  10. private cp1: Point = { x: 200, y: 30 };
  11. private cp2: Point = { x: 130, y: 80 };
  12. build() {
  13. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  14. Canvas(this.context)
  15. .width('100%')
  16. .height('100%')
  17. .backgroundColor('rgb(213,213,213)')
  18. .onReady(() => {
  19. let ctx = this.context;
  20. // Cubic Bezier curve
  21. ctx.beginPath();
  22. ctx.moveTo(this.start.x, this.start.y);
  23. ctx.bezierCurveTo(this.cp1.x, this.cp1.y, this.cp2.x, this.cp2.y, this.end.x, this.end.y);
  24. ctx.stroke();
  25. // Start point and end point
  26. ctx.fillStyle = 'rgb(39,135,217)';
  27. ctx.beginPath();
  28. ctx.arc(this.start.x, this.start.y, 5, 0, 2 * Math.PI); // Start point
  29. ctx.arc(this.end.x, this.end.y, 5, 0, 2 * Math.PI); // End point
  30. ctx.fill();
  31. // Control points
  32. ctx.fillStyle = 'rgb(23,169,141)';
  33. ctx.beginPath();
  34. ctx.arc(this.cp1.x, this.cp1.y, 5, 0, 2 * Math.PI); // Control point 1
  35. ctx.arc(this.cp2.x, this.cp2.y, 5, 0, 2 * Math.PI); // Control point 2
  36. ctx.fill();
  37. })
  38. }
  39. .width('100%')
  40. .height('100%')
  41. }
  42. }

quadraticCurveTo

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void

Create a path for a quadratic Bezier curve.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
cpx number Yes

X-coordinate of the Bezier curve parameter.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

cpy number Yes

Y-coordinate of the Bezier curve parameter.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

x number Yes

X-coordinate of the end point on the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Y-coordinate of the end point on the Bezier curve.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { Point } from '@kit.TestKit';
  3. @Entry
  4. @Component
  5. struct QuadraticCurveTo {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. private start: Point = { x: 50, y: 20 };
  9. private end: Point = { x: 50, y: 100 };
  10. private cp: Point = { x: 230, y: 30 };
  11. build() {
  12. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  13. Canvas(this.context)
  14. .width('100%')
  15. .height('100%')
  16. .backgroundColor('rgb(213,213,213)')
  17. .onReady(() => {
  18. let ctx = this.context;
  19. // Quadratic Bezier curve
  20. ctx.beginPath();
  21. ctx.moveTo(this.start.x, this.start.y);
  22. ctx.quadraticCurveTo(this.cp.x, this.cp.y, this.end.x, this.end.y);
  23. ctx.stroke();
  24. // Start point and end point
  25. ctx.fillStyle = 'rgb(39,135,217)';
  26. ctx.beginPath();
  27. ctx.arc(this.start.x, this.start.y, 5, 0, 2 * Math.PI); // Start point
  28. ctx.arc(this.end.x, this.end.y, 5, 0, 2 * Math.PI); // End point
  29. ctx.fill();
  30. // Control point
  31. ctx.fillStyle = 'rgb(23,169,141)';
  32. ctx.beginPath();
  33. ctx.arc(this.cp.x, this.cp.y, 5, 0, 2 * Math.PI);
  34. ctx.fill();
  35. })
  36. }
  37. .width('100%')
  38. .height('100%')
  39. }
  40. }

arc

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void

Draws an arc on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the center point of the arc.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Y-coordinate of the center point of the arc.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

radius number Yes

Radius of the arc.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

startAngle number Yes

Start radian of the arc.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Unit: radian

endAngle number Yes

End radian of the arc.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Unit: radian

counterclockwise boolean No

Whether to draw the arc counterclockwise.

true: Draw the arc counterclockwise.

false: Draw the arc clockwise.

The default value is false. If this parameter is set to null or undefined, the default value is used.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Arc {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.beginPath()
  15. this.context.arc(100, 75, 50, 0, 6.28)
  16. this.context.stroke()
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

arcTo

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void

Creates a circular arc using the given control points and radius.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x1 number Yes

X-coordinate of the first control point.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y1 number Yes

Y-coordinate of the first control point.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

x2 number Yes

X-coordinate of the second control point.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y2 number Yes

Y-coordinate of the second control point.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

radius number Yes

Radius of the arc.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ArcTo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. // Tangent
  15. this.context.beginPath()
  16. this.context.strokeStyle = '#808080'
  17. this.context.lineWidth = 1.5;
  18. this.context.moveTo(360, 20);
  19. this.context.lineTo(360, 170);
  20. this.context.lineTo(110, 170);
  21. this.context.stroke();
  22. // Arc
  23. this.context.beginPath()
  24. this.context.strokeStyle = '#000000'
  25. this.context.lineWidth = 3;
  26. this.context.moveTo(360, 20)
  27. this.context.arcTo(360, 170, 110, 170, 150)
  28. this.context.stroke()
  29. // Start point
  30. this.context.beginPath();
  31. this.context.fillStyle = '#00ff00';
  32. this.context.arc(360, 20, 4, 0, 2 * Math.PI);
  33. this.context.fill();
  34. // Control points
  35. this.context.beginPath();
  36. this.context.fillStyle = '#ff0000';
  37. this.context.arc(360, 170, 4, 0, 2 * Math.PI);
  38. this.context.arc(110, 170, 4, 0, 2 * Math.PI);
  39. this.context.fill();
  40. })
  41. }
  42. .width('100%')
  43. .height('100%')
  44. }
  45. }

In this example, the arc created by arcTo() is black, and the two tangents of the arc are gray. The control points are marked in red, and the start point is indicated in green.

You can visualize two tangents: One tangent extends from the start point to the first control point, and the other tangent extends from the first control point to the second control point. The arcTo() API creates an arc between these two tangents, ensuring that the arc is tangent to both lines at the points of contact.

ellipse

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void

Draws an ellipse in the specified rectangular region on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the ellipse center.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Y-coordinate of the ellipse center.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

radiusX number Yes

Radius of the ellipse on the x-axis.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

radiusY number Yes

Radius of the ellipse on the y-axis.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

rotation number Yes

Rotation angle of the ellipse.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Unit: radian

startAngle number Yes

Angle of the start point for drawing the ellipse.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Unit: radian

endAngle number Yes

Angle of the end point for drawing the ellipse.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Unit: radian

counterclockwise boolean No

Whether to draw the ellipse counterclockwise.

true: Draw the ellipse counterclockwise.

false: Draw the ellipse clockwise.

The default value is false. If this parameter is set to null or undefined, the default value is used.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.beginPath()
  15. this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2, false)
  16. this.context.stroke()
  17. this.context.beginPath()
  18. this.context.ellipse(200, 300, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2, true)
  19. this.context.stroke()
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

rect

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

rect(x: number, y: number, w: number, h: number): void

Creates a rectangle on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the rectangle's top-left corner.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Y-coordinate of the rectangle's top-left corner.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

w number Yes

Width of the rectangle.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

h number Yes

Height of the rectangle.

In versions earlier than API version 18, NaN or Infinity value prevents the entire path from rendering, and null or undefined value causes the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other path APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
  15. this.context.stroke()
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

roundRect20+

Phone20+PC/2in120+Tablet20+TV20+Wearable20+

roundRect(x: number, y: number, w: number, h: number, radii?: number | Array<number>): void

Creates a rounded rectangle path. This API does not directly render content. To draw the rounded rectangle on the canvas, use fill or stroke.

Widget capability: This API can be used in ArkTS widgets since API version 20.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the rectangle's top-left corner.

The value null is treated as 0, and undefined is treated as an invalid value, indicating no rendering.

To draw a complete rectangle, the value range is [0, Canvas width).

Default unit: vp

y number Yes

Y-coordinate of the rectangle's top-left corner.

The value null is treated as 0, and undefined is treated as an invalid value, indicating no rendering.

To draw a complete rectangle, the value range is [0, Canvas height).

Default unit: vp

w number Yes

Width of the rectangle. A negative value indicates that the rectangle is drawn from right to left.

The value null is treated as 0, and undefined is treated as an invalid value, indicating no rendering.

To draw a complete rectangle, the value range is [-x, Canvas width - x].

Default unit: vp

h number Yes

Height of the rectangle. A negative value indicates upward drawing.

The value null is treated as 0, and undefined is treated as an invalid value, indicating no rendering.

To draw a complete rectangle, the value range is [-y, Canvas height - y].

Default unit: vp

radii number | Array<number> No

Number or list of arc radii used for the rectangle corners.

If the parameter type is number, it applies to the arc radius of all rectangle corners.

If the parameter type is Array<number>, the array contains 1 to 4 numbers, interpreted as follows:

[Arc radius of all rectangle corners]

[Arc radius of the top-left and bottom-right rectangle corners, and arc radius of the top-right and bottom-left rectangle corners]

[Arc radius of the top-left rectangle corner, arc radius of the top-right and bottom-left rectangle corners, and arc radius of the bottom-right rectangle corner]

[Arc radius of the top-left rectangle corner, arc radius of the top-right rectangle corner, arc radius of the bottom-right rectangle corner, and arc radius of the bottom-left rectangle corner]

If radii contains a negative number or the number of items in the list is not within [1,4], error code 103701 is reported.

Default value: 0. null and undefined are treated as the default value.

If the arc radius exceeds the width and height of the rectangle, it will be proportionally scaled down to match the corresponding dimensions.

Default unit: vp

Error codes

For details about the error codes, see Canvas Component Error Codes.

Expand
ID Error Message Possible Causes
103701 Parameter error. 1. The param radii is a list that has zero or more than four elements; 2. The param radii contains negative value.

Example

The following example shows how to draw six rounded rectangles:

  1. Create a rounded rectangle with the start point at (10 vp, 10 vp), width and height of 100 vp, and arc radius of 10 vp for the four rectangle corners, and fill the rectangle.

  2. Create a rounded rectangle with the start point at (120 vp, 10 vp), width and height of 100 vp, and arc radius of 10 vp for the four rectangle corners, and fill the rectangle.

  3. Create a rounded rectangle with the start point at (10 vp, 120 vp), width and height of 100 vp, arc radius of 10 vp for the top-left and bottom-right rectangle corners, arc radius of 20 vp for the top-right and bottom-left rectangle corners, and stroke the rectangle.

  4. Create a rounded rectangle with the start point at (120 vp, 120 vp), width and height of 100 vp, arc radius of 10 vp for the top-left rectangle corner, arc radius of 20 vp for the top-right and bottom-left rectangle corners, arc radius of 30 vp for the bottom-right rectangle corner, and stroke the rectangle.

  5. Create a rounded rectangle with the start point at (10 vp, 230 vp), width and height of 100 vp, and the radius of the top-left, top-right, bottom-right, and bottom-left rounded corners of 10 vp, 20 vp, 30 vp, and 40 vp, respectively. Then, stroke the rectangle.

  6. Create a rounded rectangle with the start point at (220 vp, 330 vp), width and height of -100 vp, and the radius of the top-left, top-right, bottom-right, and bottom-left rounded corners of 10 vp, 20 vp, 30 vp, and 40 vp, respectively. Then, stroke the rectangle.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. @Entry
  4. @Component
  5. struct CanvasExample {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Canvas(this.context)
  11. .width('100%')
  12. .height('100%')
  13. .backgroundColor('#D5D5D5')
  14. .onReady(() => {
  15. try {
  16. this.context.fillStyle = '#707070'
  17. this.context.beginPath()
  18. // Create a rounded rectangle with the start point at (10 vp, 10 vp), width and height of 100 vp, and arc radius of 10 vp for the four rectangle corners.
  19. this.context.roundRect(10, 10, 100, 100, 10)
  20. // Create a rounded rectangle with the start point at (120 vp, 10 vp), width and height of 100 vp, and arc radius of 10 vp for the four rectangle corners.
  21. this.context.roundRect(120, 10, 100, 100, [10])
  22. this.context.fill()
  23. this.context.beginPath()
  24. // Create a rounded rectangle with the start point at (10 vp, 120 vp), width and height of 100 vp, arc radius of 10 vp for the top-left and bottom-right rectangle corners, and arc radius of 20 vp for the top-right and bottom-left rectangle corners.
  25. this.context.roundRect(10, 120, 100, 100, [10, 20])
  26. // Create a rounded rectangle with the start point at (120 vp, 120 vp), width and height of 100 vp, arc radius of 10 vp for the top-left rectangle corner, arc radius of 20 vp for the top-right and bottom-left rectangle corners, and arc radius of 30 vp for the bottom-right rectangle corner.
  27. this.context.roundRect(120, 120, 100, 100, [10, 20, 30])
  28. // Create a rounded rectangle with the start point at (10 vp, 230 vp), width and height of 100 vp, and the radius of the top-left, top-right, bottom-right, and bottom-left rounded corners of 10 vp, 20 vp, 30 vp, and 40 vp, respectively.
  29. this.context.roundRect(10, 230, 100, 100, [10, 20, 30, 40])
  30. // Create a rounded rectangle with the start point at (220 vp, 330 vp), width and height of -100 vp, and the radius of the top-left, top-right, bottom-right, and bottom-left rounded corners of 10 vp, 20 vp, 30 vp, and 40 vp, respectively.
  31. this.context.roundRect(220, 330, -100, -100, [10, 20, 30, 40])
  32. this.context.stroke()
  33. } catch (error) {
  34. let e: BusinessError = error as BusinessError;
  35. console.error(`Failed to create roundRect. Code: ${e.code}, message: ${e.message}`);
  36. }
  37. })
  38. }
  39. .width('100%')
  40. .height('100%')
  41. }
  42. }

fill

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

fill(fillRule?: CanvasFillRule): void

Fills the current path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
fillRule CanvasFillRule No

Rule by which to determine whether a point is inside or outside the area to fill.

The options are "nonzero" and "evenodd".

Invalid values undefined and null are treated as the default value.

Default value: "nonzero"

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Fill {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
  15. this.context.fill()
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

fill

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

fill(path: Path2D, fillRule?: CanvasFillRule): void

Fills a specified path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
path Path2D Yes

Path2D path to fill.

undefined and null are treated as invalid values.

fillRule CanvasFillRule No

Rule by which to determine whether a point is inside or outside the area to fill.

The options are "nonzero" and "evenodd".

Invalid values undefined and null are treated as the default value.

Default value: "nonzero"

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Fill {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. let region = new Path2D()
  15. region.moveTo(30, 90)
  16. region.lineTo(110, 20)
  17. region.lineTo(240, 130)
  18. region.lineTo(60, 130)
  19. region.lineTo(190, 20)
  20. region.lineTo(270, 90)
  21. region.closePath()
  22. // Fill path
  23. this.context.fillStyle = '#00ff00'
  24. this.context.fill(region, "evenodd")
  25. })
  26. }
  27. .width('100%')
  28. .height('100%')
  29. }
  30. }

clip

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

clip(fillRule?: CanvasFillRule): void

Sets the current path to a clipping path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
fillRule CanvasFillRule No

Rule by which to determine whether a point is inside or outside the area to clip.

The options are "nonzero" and "evenodd".

Invalid values undefined and null are treated as the default value.

Default value: "nonzero"

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Clip {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.rect(0, 0, 100, 200)
  15. this.context.stroke()
  16. this.context.clip()
  17. this.context.fillStyle = "rgb(255,0,0)"
  18. this.context.fillRect(0, 0, 200, 200)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

clip

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

clip(path: Path2D, fillRule?: CanvasFillRule): void

Sets a specified path as the clipping path.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
path Path2D Yes

Path2D path to clip.

undefined and null are treated as invalid values.

fillRule CanvasFillRule No

Rule by which to determine whether a point is inside or outside the area to clip.

The options are "nonzero" and "evenodd".

Invalid values undefined and null are treated as the default value.

Default value: "nonzero"

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Clip {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. let region = new Path2D()
  15. region.moveTo(30, 90)
  16. region.lineTo(110, 20)
  17. region.lineTo(240, 130)
  18. region.lineTo(60, 130)
  19. region.lineTo(190, 20)
  20. region.lineTo(270, 90)
  21. region.closePath()
  22. this.context.clip(region, "evenodd")
  23. this.context.fillStyle = "rgb(0,255,0)"
  24. this.context.fillRect(0, 0, this.context.width, this.context.height)
  25. })
  26. }
  27. .width('100%')
  28. .height('100%')
  29. }
  30. }

reset12+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

reset(): void

Resets this CanvasRenderingContext2D object to its default state and clears the background buffer, drawing state stack, defined paths, and styles.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Reset {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.fillStyle = '#0000ff'
  15. this.context.fillRect(20, 20, 150, 100)
  16. this.context.reset()
  17. this.context.fillRect(20, 150, 150, 100)
  18. })
  19. }
  20. .width('100%')
  21. .height('100%')
  22. }
  23. }

saveLayer12+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

saveLayer(): void

Saves this layer.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct saveLayer {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() =>{
  14. this.context.fillStyle = "#0000ff"
  15. this.context.fillRect(50,100,300,100)
  16. this.context.fillStyle = "#00ffff"
  17. this.context.fillRect(50,150,300,100)
  18. this.context.globalCompositeOperation = 'destination-over'
  19. this.context.saveLayer()
  20. this.context.globalCompositeOperation = 'source-over'
  21. this.context.fillStyle = "#ff0000"
  22. this.context.fillRect(100,50,100,300)
  23. this.context.fillStyle = "#00ff00"
  24. this.context.fillRect(150,50,100,300)
  25. this.context.restoreLayer()
  26. })
  27. }
  28. .width('100%')
  29. .height('100%')
  30. }
  31. }

restoreLayer12+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

restoreLayer(): void

Restores the image transformation and cropping state to the state before saveLayer, and then draws the layer onto the canvas. For the sample code, see the code for saveLayer.

System capability: SystemCapability.ArkUI.ArkUI.Full

resetTransform

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

resetTransform(): void

Resets the current transform to the identity matrix.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ResetTransform {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.setTransform(1, 0.5, -0.5, 1, 10, 10)
  15. this.context.fillStyle = 'rgb(0,0,255)'
  16. this.context.fillRect(0, 0, 100, 100)
  17. this.context.resetTransform()
  18. this.context.fillStyle = 'rgb(255,0,0)'
  19. this.context.fillRect(0, 0, 100, 100)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

rotate

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

rotate(angle: number): void

Rotates a canvas clockwise around its coordinate axes.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
angle number Yes

Clockwise rotation angle. You can convert degrees to radians using the following formula: degree * Math.PI/180.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Unit: radian

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Rotate {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.rotate(45 * Math.PI / 180)
  15. this.context.fillRect(70, 20, 50, 50)
  16. })
  17. }
  18. .width('100%')
  19. .height('100%')
  20. }
  21. }

scale

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

scale(x: number, y: number): void

Scales the canvas based on the given scale factors.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

Horizontal scale factor.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values 0, null, undefined, and negative numbers cause the current API to have no effect. Since API version 18, NaN, Infinity, 0, null, undefined, and negative numbers cause the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

y number Yes

Vertical scaling factor. Negative numbers are not supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values 0, null, undefined, and negative numbers cause the current API to have no effect. Since API version 18, NaN, Infinity, 0, null, undefined, and negative numbers cause the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Scale {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.lineWidth = 3
  15. this.context.strokeRect(30, 30, 50, 50)
  16. this.context.scale(2, 2) // Scale to 200%
  17. this.context.strokeRect(30, 30, 50, 50)
  18. })
  19. }
  20. .width('100%')
  21. .height('100%')
  22. }
  23. }

transform

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

transform(a: number, b: number, c: number, d: number, e: number, f: number): void

Defines 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.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

NOTE

The coordinates of each point in the graph after transformation can be calculated using the following formula:

x and y represent coordinates before transformation, and x' and y' represent coordinates after transformation.

  • x' = a * x + c * y + e

  • y' = b * x + d * y + f

Parameters

Expand
Name Type Mandatory Description
a number Yes

Cell at row 1, column 1 of the transformation matrix. scaleX: horizontal scaling value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

b number Yes

Cell at row 2, column 1 of the transformation matrix. skewY: vertical skewing value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

c number Yes

Cell at row 1, column 2 of the transformation matrix. skewX: horizontal skewing value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

d number Yes

Cell at row 2, column 2 of the transformation matrix. scaleY: vertical scaling value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

e number Yes

Cell at row 1, column 3 of the transformation matrix. translateX: horizontal translation distance. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Default unit: vp

f number Yes

Cell at row 2, column 3 of the transformation matrix. translateY: vertical translation distance. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Transform {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.fillStyle = 'rgb(112,112,112)'
  15. this.context.fillRect(0, 0, 100, 100)
  16. this.context.transform(1, 0.5, -0.5, 1, 10, 10)
  17. this.context.fillStyle = 'rgb(0,74,175)'
  18. this.context.fillRect(0, 0, 100, 100)
  19. this.context.transform(1, 0.5, -0.5, 1, 10, 10)
  20. this.context.fillStyle = 'rgb(39,135,217)'
  21. this.context.fillRect(0, 0, 100, 100)
  22. })
  23. }
  24. .width('100%')
  25. .height('100%')
  26. }
  27. }

setTransform

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void

Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the transform() API.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

NOTE

The coordinates of each point in the graph after transformation can be calculated using the following formula:

x and y represent coordinates before transformation, and x' and y' represent coordinates after transformation.

  • x' = a * x + c * y + e

  • y' = b * x + d * y + f

Parameters

Expand
Name Type Mandatory Description
a number Yes

scaleX: horizontal scaling value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

b number Yes

skewY: vertical skewing value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

c number Yes

skewX: horizontal skewing value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

d number Yes

scaleY: vertical scaling value. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

e number Yes

translateX: horizontal translation distance. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Default unit: vp

f number Yes

translateY: vertical translation distance. A negative value is supported.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct SetTransform {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. this.context.fillStyle = 'rgb(112,112,112)'
  15. this.context.fillRect(0, 0, 100, 100)
  16. this.context.transform(1, 0.5, -0.5, 1, 10, 10)
  17. this.context.fillStyle = 'rgb(23,169,141)'
  18. this.context.fillRect(0, 0, 100, 100)
  19. this.context.setTransform(1, 0.5, -0.5, 1, 10, 10)
  20. this.context.fillStyle = 'rgb(39,135,217)'
  21. this.context.fillRect(0, 0, 100, 100)
  22. })
  23. }
  24. .width('100%')
  25. .height('100%')
  26. }
  27. }

setTransform

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

setTransform(transform?: Matrix2D): void

Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified Matrix2D object.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
transform Matrix2D No

Transformation matrix.

undefined and null are treated as invalid values.

Default value: null

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct TransFormDemo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Text('context1');
  11. Canvas(this.context1)
  12. .width('230vp')
  13. .height('160vp')
  14. .backgroundColor('#ffff00')
  15. .onReady(() =>{
  16. this.context1.fillRect(100, 20, 50, 50);
  17. this.context1.setTransform(1, 0.5, -0.5, 1, 10, 10);
  18. this.context1.fillRect(100, 20, 50, 50);
  19. })
  20. Text('context2');
  21. Canvas(this.context2)
  22. .width('230vp')
  23. .height('160vp')
  24. .backgroundColor('#0ffff0')
  25. .onReady(() =>{
  26. this.context2.fillRect(100, 20, 50, 50);
  27. let storedTransform = this.context1.getTransform();
  28. this.context2.setTransform(storedTransform);
  29. this.context2.fillRect(100, 20, 50, 50);
  30. })
  31. }
  32. .width('100%')
  33. .height('100%')
  34. }
  35. }

getTransform

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

getTransform(): Matrix2D

Obtains the current transformation matrix being applied to the context.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Expand
Type Description
Matrix2D Current transformation matrix applied to the context.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct TransFormDemo {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Text('context1');
  11. Canvas(this.context1)
  12. .width('230vp')
  13. .height('120vp')
  14. .backgroundColor('#ffff00')
  15. .onReady(() => {
  16. this.context1.fillRect(50, 50, 50, 50);
  17. this.context1.setTransform(1.2, Math.PI / 8, Math.PI / 6, 0.5, 30, -25);
  18. this.context1.fillRect(50, 50, 50, 50);
  19. })
  20. Text('context2');
  21. Canvas(this.context2)
  22. .width('230vp')
  23. .height('120vp')
  24. .backgroundColor('#0ffff0')
  25. .onReady(() => {
  26. this.context2.fillRect(50, 50, 50, 50);
  27. let storedTransform = this.context1.getTransform();
  28. console.info(`Matrix [scaleX = ${storedTransform.scaleX}, scaleY = ${storedTransform.scaleY}, rotateX = ${storedTransform.rotateX}, rotateY = ${storedTransform.rotateY}, translateX = ${storedTransform.translateX}, translateY = ${storedTransform.translateY}]`)
  29. this.context2.setTransform(storedTransform);
  30. this.context2.fillRect(50, 50, 50, 50);
  31. })
  32. }
  33. .width('100%')
  34. .height('100%')
  35. }
  36. }

translate

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

translate(x: number, y: number): void

Moves the origin of the coordinate system.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

Distance to translate on the x-axis.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Default unit: vp

y number Yes

Distance to translate on the y-axis.

In versions earlier than API version 18, values NaN and Infinity cause the failure to call the drawing APIs following this API for rendering. Values null and undefined cause the current API to have no effect. Since API version 18, NaN, Infinity, null, or undefined causes the current API to have no effect, and other drawing APIs with valid arguments continue to render correctly.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Translate {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() => {
  14. this.context.fillRect(10, 10, 50, 50)
  15. this.context.translate(70, 70)
  16. this.context.fillRect(10, 10, 50, 50)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

drawImage

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void

Draws an image on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9, except that PixelMap objects are not supported.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
image ImageBitmap | PixelMap Yes

Image resource. For details, see ImageBitmap or PixelMap.

undefined and null are treated as invalid values and no rendering will be performed.

dx number Yes

X-coordinate of the top-left corner of the drawing area on the canvas.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

dy number Yes

Y-coordinate of the top-left corner of the drawing area on the canvas.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

Example

NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ImageExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. // Replace "common/images/example.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#D5D5D5')
  15. .onReady(() => {
  16. this.context.drawImage(this.img, 0, 0)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

drawImage

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dw: number, dh: number): void

Draws an image by stretching or compressing it to the specified dimensions.

Widget capability: This API can be used in ArkTS widgets since API version 9, except that PixelMap objects are not supported.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
image ImageBitmap | PixelMap Yes

Image resource. For details, see ImageBitmap or PixelMap.

undefined and null are treated as invalid values and no rendering will be performed.

dx number Yes

X-coordinate of the top-left corner of the drawing area on the canvas.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

dy number Yes

Y-coordinate of the top-left corner of the drawing area on the canvas.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

dw number Yes

Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.

Negative values, undefined, and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

dh number Yes

Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.

Negative values, undefined, and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

Example

NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ImageExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. // Replace "common/images/example.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#D5D5D5')
  15. .onReady(() => {
  16. this.context.drawImage(this.img, 0, 0, 300, 300)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

drawImage

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void

Draws a cropped portion of an image by stretching or compressing it to the specified dimensions.

Widget capability: This API can be used in ArkTS widgets since API version 9, except that PixelMap objects are not supported.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
image ImageBitmap | PixelMap Yes

Image resource. For details, see ImageBitmap or PixelMap.

undefined and null are treated as invalid values and no rendering will be performed.

sx number Yes

X-coordinate of the top-left corner of the rectangle used to crop the source image.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

If the type of image is ImageBitmap, the default unit is vp.

If the type of image is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later.

sy number Yes

Y-coordinate of the top-left corner of the rectangle used to crop the source image.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

If the type of image is ImageBitmap, the default unit is vp.

If the type of image is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later.

sw number Yes

Target width to crop the source image.

Negative values, undefined, and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

If the type of image is ImageBitmap, the default unit is vp.

If the type of image is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later.

sh number Yes

Target height to crop the source image.

Negative values, undefined, and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

If the type of image is ImageBitmap, the default unit is vp.

If the type of image is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later.

dx number Yes

X-coordinate of the top-left corner of the drawing area on the canvas.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

dy number Yes

Y-coordinate of the top-left corner of the drawing area on the canvas.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed.

Default unit: vp

dw number Yes

Width of the drawing area.

Negative values, undefined, and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed. 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.

Default unit: vp

dh number Yes

Height of the drawing area.

Negative values, undefined, and null are treated as 0. NaN and Infinity are treated as invalid and no rendering will be performed. 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.

Default unit: vp

Example

NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ImageExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. // Replace "common/images/example.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#D5D5D5')
  15. .onReady(() => {
  16. this.context.drawImage(this.img, 0, 0, 500, 500, 0, 0, 400, 300)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

createImageData

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createImageData(sw: number, sh: number): ImageData

Creates a blank ImageData object of a specified size. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it. The createImageData example is identical to the putImageData example.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
sw number Yes

Width of the ImageData object.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

sh number Yes

Height of the ImageData object.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

Return value

Expand
Type Description
ImageData New ImageData object.

createImageData

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createImageData(imageData: ImageData): ImageData

Creates an ImageData object with the same width and height of an existing ImageData object. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it. The createImageData example is identical to the putImageData example.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
imageData ImageData Yes

Existing ImageData object.

Values undefined and null are treated as ImageData with its width and height set to 0.

Return value

Expand
Type Description
ImageData New ImageData object.

getPixelMap

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap

Obtains the PixelMap object created with the pixels within the specified area on the canvas. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
sx number Yes

X-coordinate of the top-left corner of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

sy number Yes

Y-coordinate of the top-left corner of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

sw number Yes

Width of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

sh number Yes

Height of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

Return value

Expand
Type Description
PixelMap PixelMap object.

Example

NOTE
  • The DevEco Studio Previewer does not support displaying content drawn with setPixelMap.

  • The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct GetPixelMap {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. // Replace "common/images/example.jpg" with the image resource file you use.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg")
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#ffff00')
  15. .onReady(() => {
  16. this.context.drawImage(this.img, 100, 100, 130, 130)
  17. let pixelmap = this.context.getPixelMap(150, 150, 130, 130)
  18. this.context.setPixelMap(pixelmap)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

setPixelMap

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

setPixelMap(value?: PixelMap): void

Draws the input PixelMap object on the canvas. The example is the same as that of getPixelMap.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
value PixelMap No

PixelMap object that contains pixel values.

undefined and null are treated as invalid values and no rendering will be performed.

Default value: null

getImageData

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

getImageData(sx: number, sy: number, sw: number, sh: number): ImageData

Obtains the ImageData object created with the pixels within the specified area on the canvas. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
sx number Yes

X-coordinate of the top-left corner of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

sy number Yes

Y-coordinate of the top-left corner of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

sw number Yes

Width of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

sh number Yes

Height of the output area.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

Return value

Expand
Type Description
ImageData New ImageData object.

Example

NOTE

The resources used in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, the resources that are located outside the resources directory are not packaged by default when a project or module is created. To package these resources, go to buildOption in the module's build-profile.json5 file > resOptions > copyCodeResource, and set enable to true. For details, see the description of copyCodeResource in resOptions.

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct GetImageData {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. // Replace "/common/images/1234.png" with the image resource file you use.
  8. private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
  9. build() {
  10. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  11. Canvas(this.context)
  12. .width('100%')
  13. .height('100%')
  14. .backgroundColor('#ffff00')
  15. .onReady(() =>{
  16. this.context.drawImage(this.img,0,0,130,130)
  17. let imageData = this.context.getImageData(50,50,130,130)
  18. this.context.putImageData(imageData,150,150)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

putImageData

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

putImageData(imageData: ImageData, dx: number | string, dy: number | string): void

Puts an ImageData object onto a rectangular area on the canvas.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
imageData ImageData Yes

ImageData object with pixels to put onto the canvas.

undefined and null are treated as invalid values and no rendering will be performed.

dx number | string10+ Yes

X-axis offset of the rectangular area on the canvas.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

dy number | string10+ Yes

Y-axis offset of the rectangular area on the canvas.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct PutImageData {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. let imageDataNum = this.context.createImageData(100, 100)
  15. let imageData = this.context.createImageData(imageDataNum)
  16. for (let i = 0; i < imageData.data.length; i += 4) {
  17. imageData.data[i + 0] = 112
  18. imageData.data[i + 1] = 112
  19. imageData.data[i + 2] = 112
  20. imageData.data[i + 3] = 255
  21. }
  22. this.context.putImageData(imageData, 10, 10)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

putImageData

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

putImageData(imageData: ImageData, dx: number | string, dy: number | string, dirtyX: number | string, dirtyY: number | string, dirtyWidth: number | string, dirtyHeight: number | string): void

Fills the new rectangular area with the ImageData data after cropping.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
imageData ImageData Yes

ImageData object with pixels to put onto the canvas.

undefined and null are treated as invalid values and no rendering will be performed.

dx number | string10+ Yes

X-axis offset of the rectangular area on the canvas.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

dy number | string10+ Yes

Y-axis offset of the rectangular area on the canvas.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

dirtyX number | string10+ Yes

X-axis offset of the upper left corner of the rectangular area relative to that of the source image.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

dirtyY number | string10+ Yes

Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

dirtyWidth number | string10+ Yes

Width of the rectangular area to crop the source image.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

dirtyHeight number | string10+ Yes

Height of the rectangular area to crop the source image.

Invalid values undefined, null, NaN, and Infinity are treated as 0.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct PutImageData {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. let imageDataNum = this.context.createImageData(100, 100)
  15. let imageData = this.context.createImageData(imageDataNum)
  16. for (let i = 0; i < imageData.data.length; i += 4) {
  17. imageData.data[i + 0] = 112
  18. imageData.data[i + 1] = 112
  19. imageData.data[i + 2] = 112
  20. imageData.data[i + 3] = 255
  21. }
  22. this.context.putImageData(imageData, 10, 10, 0, 0, 100, 50)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

setLineDash

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

setLineDash(segments: number[]): void

Sets the dash line style.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
segments number[] Yes

An array of numbers that specify distances to alternately draw a line and a gap.

undefined and null are treated as invalid values.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct SetLineDash {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#D5D5D5')
  13. .onReady(() =>{
  14. this.context.arc(100, 75, 50, 0, 6.28)
  15. this.context.setLineDash([10,20])
  16. this.context.stroke()
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

getLineDash

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

getLineDash(): number[]

Obtains the dash line style.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Expand
Type Description
number[]

Interval of alternate line segments and the length of spacing.

Default unit: vp

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasGetLineDash {
  5. @State message: string = 'Hello World'
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  8. build() {
  9. Row() {
  10. Column() {
  11. Text(this.message)
  12. .fontSize(50)
  13. .fontWeight(FontWeight.Bold)
  14. Canvas(this.context)
  15. .width('100%')
  16. .height('100%')
  17. .backgroundColor('#D5D5D5')
  18. .onReady(() => {
  19. this.context.arc(100, 75, 50, 0, 6.28)
  20. this.context.setLineDash([10, 20])
  21. this.context.stroke()
  22. let res = this.context.getLineDash()
  23. this.message = JSON.stringify(res)
  24. })
  25. }
  26. .width('100%')
  27. }
  28. .height('100%')
  29. }
  30. }

transferFromImageBitmap

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

transferFromImageBitmap(bitmap: ImageBitmap): void

Displays the specified ImageBitmap object.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
bitmap ImageBitmap Yes ImageBitmap object to display.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct TransferFromImageBitmap {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Canvas(this.context)
  11. .width('100%')
  12. .height('100%')
  13. .backgroundColor('rgb(213,213,213)')
  14. .onReady(() =>{
  15. let imageData = this.offContext.createImageData(100, 100)
  16. for (let i = 0; i < imageData.data.length; i += 4) {
  17. imageData.data[i + 0] = 255
  18. imageData.data[i + 1] = 0
  19. imageData.data[i + 2] = 60
  20. imageData.data[i + 3] = 80
  21. }
  22. this.offContext.putImageData(imageData, 10, 10)
  23. let image = this.offContext.transferToImageBitmap()
  24. this.context.transferFromImageBitmap(image)
  25. })
  26. }
  27. .width('100%')
  28. .height('100%')
  29. }
  30. }

toDataURL

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

toDataURL(type?: string, quality?: any): string

Creates a data URL that contains a representation of an image. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
type string No

Image format.

The options are image/png, image/jpeg, and image/webp.

Invalid values undefined and null are treated as the default value.

Default value: image/png

quality any No

Image quality, which ranges from 0 to 1, when the image format is image/jpeg or image/webp. If the set value is beyond the value range, the default value 0.92 is used.

Invalid values undefined, null, NaN, and Infinity are treated as the default value.

Default value: 0.92

Return value

Expand
Type Description
string Image URL.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. @State toDataURL: string = ""
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Canvas(this.context)
  11. .width(100)
  12. .height(100)
  13. .onReady(() =>{
  14. this.context.fillStyle = "#00ff00"
  15. this.context.fillRect(0,0,100,100)
  16. this.toDataURL = this.context.toDataURL("image/png", 0.92)
  17. })
  18. Text(this.toDataURL)
  19. }
  20. .width('100%')
  21. .height('100%')
  22. .backgroundColor('#ffff00')
  23. }
  24. }

restore

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

restore(): void

Restores the saved drawing context.

NOTE

When the number of calls to restore() does not exceed the number of calls to save(), this API pops the saved drawing state from the stack and restores the attributes, clipping path, and transformation matrix of the CanvasRenderingContext2D object.

If the number of calls to restore() exceeds the number of calls to save(), this API does nothing.

If there is no saved state, this API does nothing.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() =>{
  14. this.context.save() // save the default state
  15. this.context.fillStyle = "#00ff00"
  16. this.context.fillRect(20, 20, 100, 100)
  17. this.context.restore() // restore to the default state
  18. this.context.fillRect(150, 75, 100, 100)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

save

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

save(): void

Saves all states of the canvas in the stack. This API is usually called when the drawing state needs to be saved.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffff00')
  13. .onReady(() =>{
  14. this.context.save() // save the default state
  15. this.context.fillStyle = "#00ff00"
  16. this.context.fillRect(20, 20, 100, 100)
  17. this.context.restore() // restore to the default state
  18. this.context.fillRect(150, 75, 100, 100)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

createLinearGradient

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient

Creates a linear gradient.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x0 number Yes

X-coordinate of the start point.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

y0 number Yes

Y-coordinate of the start point.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

x1 number Yes

X-coordinate of the end point.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

y1 number Yes

Y-coordinate of the end point.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

Return value

Expand
Type Description
CanvasGradient New CanvasGradient object used to create a gradient on the canvas.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CreateLinearGradient {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() =>{
  14. let grad = this.context.createLinearGradient(50,0, 300,100)
  15. grad.addColorStop(0.0, 'rgb(39,135,217)')
  16. grad.addColorStop(0.5, 'rgb(255,238,240)')
  17. grad.addColorStop(1.0, 'rgb(23,169,141)')
  18. this.context.fillStyle = grad
  19. this.context.fillRect(0, 0, 400, 400)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

createRadialGradient

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient

Creates a radial gradient.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x0 number Yes

X-coordinate of the center of the start circle.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

y0 number Yes

Y-coordinate of the center of the start circle.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

r0 number Yes

Radius of the start circle, which must be a non-negative finite number.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

x1 number Yes

X-coordinate of the center of the end circle.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

y1 number Yes

Y-coordinate of the center of the end circle.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

r1 number Yes

Radius of the end circle, which must be a non-negative finite number.

If the value is undefined or null, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

Return value

Expand
Type Description
CanvasGradient New CanvasGradient object used to create a gradient on the canvas.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CreateRadialGradient {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('rgb(213,213,213)')
  13. .onReady(() => {
  14. let grad = this.context.createRadialGradient(200, 200, 50, 200, 200, 200)
  15. grad.addColorStop(0.0, 'rgb(39,135,217)')
  16. grad.addColorStop(0.5, 'rgb(255,238,240)')
  17. grad.addColorStop(1.0, 'rgb(112,112,112)')
  18. this.context.fillStyle = grad
  19. this.context.fillRect(0, 0, 440, 440)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

createConicGradient10+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createConicGradient(startAngle: number, x: number, y: number): CanvasGradient

Creates a conic gradient.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
startAngle number Yes

Angle at which the gradient starts. The angle measurement starts horizontally from the right side of the center and moves clockwise.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid.

Unit: radian

x number Yes

X-coordinate of the center of the conic gradient.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid.

Default unit: vp

y number Yes

Y-coordinate of the center of the conic gradient.

Invalid values undefined and null are treated as 0. NaN and Infinity are treated as invalid.

Default unit: vp

Return value

Expand
Type Description
CanvasGradient New CanvasGradient object used to create a gradient on the canvas.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct CanvasExample {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7. build() {
  8. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9. Canvas(this.context)
  10. .width('100%')
  11. .height('100%')
  12. .backgroundColor('#ffffff')
  13. .onReady(() => {
  14. let grad = this.context.createConicGradient(0, 50, 80)
  15. grad.addColorStop(0.0, 'rgb(39,135,217)')
  16. grad.addColorStop(0.5, 'rgb(213,213,213)')
  17. grad.addColorStop(1.0, 'rgb(23,160,141)')
  18. this.context.fillStyle = grad
  19. this.context.fillRect(0, 30, 100, 100)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

on('onAttach')13+

on(type: 'onAttach', callback: () => void): void

Subscribes to the event when a CanvasRenderingContext2D object is bound to a Canvas component.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
type string Yes

Event type, which is 'onAttach' in this case.

undefined and null are treated as invalid values.

callback () => void Yes

Callback triggered when the CanvasRenderingContext2D object is bound to the Canvas component.

undefined and null are treated as invalid values.

NOTE

A CanvasRenderingContext2D object can only be bound to one Canvas component at a time.

When a CanvasRenderingContext2D object is bound to a Canvas component, the onAttach callback is triggered, indicating that the canvas object is accessible.

Avoid performing drawing operations in the onAttach callback. Make sure the Canvas component has completed its onReady event before performing any drawing.

The onAttach callback is triggered when:

  1. A Canvas component is created and bound to a CanvasRenderingContext2D object.

  2. A CanvasRenderingContext2D object is bound to a new Canvas component.

on('onDetach')13+

on(type: 'onDetach', callback: () => void): void

Subscribes to the event when a CanvasRenderingContext2D object is unbound from a Canvas component.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
type string Yes

Event type, which is 'onDetach' in this case.

undefined and null are treated as invalid values.

callback () => void Yes

Callback triggered when the CanvasRenderingContext2D object is unbound from the Canvas component.

undefined and null are treated as invalid values.

NOTE

When a CanvasRenderingContext2D object is unbound from a Canvas component, the onDetach callback is triggered. In this case, cease any drawing operations.

The onDetach callback is triggered when:

  1. A Canvas component is destroyed and unbound from a CanvasRenderingContext2D object.

  2. A CanvasRenderingContext2D object is bound to a different** Canvas** component, causing the existing binding to be released.

off('onAttach')13+

off(type: 'onAttach', callback?: () => void): void

Unsubscribes from the event when a CanvasRenderingContext2D object is bound to a Canvas component.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
type string Yes

Event type, which is 'onAttach' in this case.

undefined and null are treated as invalid values.

callback () => void No

If this parameter is left empty, all callbacks triggered after the CanvasRenderingContext2D object is bound to the Canvas component are unsubscribed.

If this parameter is not left empty, the callback corresponding to the bind event is unsubscribed.

undefined and null are treated as invalid values.

off('onDetach')13+

off(type: 'onDetach', callback?: () => void): void

Unsubscribes from the event when a CanvasRenderingContext2D object is unbound from a Canvas component.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
type string Yes

Event type, which is 'onDetach' in this case.

undefined and null are treated as invalid values.

callback () => void No

If this parameter is left empty, all callbacks triggered after the CanvasRenderingContext2D object is unbound from the Canvas component are unsubscribed.

If this parameter is not left empty, the callback corresponding to the unbind event is unsubscribed.

undefined and null are treated as invalid values.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. import { FrameNode } from '@kit.ArkUI'
  3. // xxx.ets
  4. @Entry
  5. @Component
  6. struct AttachDetachExample {
  7. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  8. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  9. private scroller: Scroller = new Scroller()
  10. private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  11. private node: FrameNode | null = null
  12. attachCallback = () => {
  13. console.info('CanvasRenderingContext2D attached to the canvas frame node.')
  14. this.node = this.context.canvas
  15. }
  16. detachCallback = () => {
  17. console.info('CanvasRenderingContext2D detach from the canvas frame node.')
  18. this.node = null
  19. }
  20. aboutToAppear(): void {
  21. try {
  22. this.context.on('onAttach', this.attachCallback)
  23. this.context.on('onDetach', this.detachCallback)
  24. } catch (error) {
  25. let e: BusinessError = error as BusinessError;
  26. console.error(`Error code: ${e.code}, message: ${e.message}`);
  27. }
  28. }
  29. aboutToDisappear(): void {
  30. try {
  31. this.context.off('onAttach')
  32. this.context.off('onDetach')
  33. } catch (error) {
  34. let e: BusinessError = error as BusinessError;
  35. console.error(`Error code: ${e.code}, message: ${e.message}`);
  36. }
  37. }
  38. build() {
  39. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  40. Scroll(this.scroller) {
  41. Flex({ direction: FlexDirection.Column }) {
  42. ForEach(this.arr, (item: number) => {
  43. Row() {
  44. if (item == 3) {
  45. Canvas(this.context)
  46. .width('100%')
  47. .height(150)
  48. .backgroundColor('rgb(213,213,213)')
  49. .onReady(() => {
  50. this.context.font = '30vp sans-serif'
  51. this.node?.commonEvent.setOnVisibleAreaApproximateChange(
  52. { ratios: [0, 1], expectedUpdateInterval: 10 },
  53. (isVisible: boolean, currentRatio: number) => {
  54. if (!isVisible && currentRatio <= 0.0) {
  55. console.info('Canvas is completely invisible.')
  56. }
  57. if (isVisible && currentRatio >= 1.0) {
  58. console.info('Canvas is fully visible.')
  59. }
  60. }
  61. )
  62. })
  63. } else {
  64. Text(item.toString())
  65. .width('100%')
  66. .height(150)
  67. .backgroundColor('rgb(39,135,217)')
  68. .borderRadius(15)
  69. .fontSize(16)
  70. .textAlign(TextAlign.Center)
  71. .margin({ top: 5 })
  72. }
  73. }
  74. }, (item: number) => item.toString())
  75. }
  76. }
  77. .width('90%')
  78. .scrollBar(BarState.Off)
  79. .scrollable(ScrollDirection.Vertical)
  80. }
  81. .width('100%')
  82. .height('100%')
  83. }
  84. }

startImageAnalyzer12+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

startImageAnalyzer(config: ImageAnalyzerConfig): Promise<void>

Configures and starts the AI analyzer. This API uses a promise to return the result. Before use, set enableAnalyzer to true to enable the image AI analyzer.

Because the image frame used for analysis is the one captured when this API is called, pay attention to the invoking time of this API.

Repeated calls to this method before completion trigger an error callback. For the sample code, see the code for stopImageAnalyzer.

NOTE

The image analysis type cannot be dynamically modified.

When image changes are detected, the analysis result is automatically destroyed. You can call this API again to start analysis.

This API depends on device capabilities. If it is called on an incompatible device, an error code is returned.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
config ImageAnalyzerConfig Yes

Settings of the AI analyzer.

undefined and null are treated as invalid values.

Return value

Expand
Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see AI Image Analyzer Error Codes.

Expand
ID Error Message
110001 Image analysis feature is unsupported.
110002 Image analysis is currently being executed.
110003 Image analysis is stopped.

stopImageAnalyzer12+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

stopImageAnalyzer(): void

Stops AI image analysis. The content displayed by the AI image analyzer will be destroyed.

NOTE

If this API is called when the startImageAnalyzer API has not yet returned any result, an error is reported.

This feature depends on device capabilities.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. @Entry
  4. @Component
  5. struct ImageAnalyzerExample {
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true)
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  8. private config: ImageAnalyzerConfig = {
  9. types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT]
  10. }
  11. // Replace 'common/images/example.png' with the image resource file you use.
  12. private img = new ImageBitmap('common/images/example.png')
  13. private aiController: ImageAnalyzerController = new ImageAnalyzerController()
  14. private options: ImageAIOptions = {
  15. types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
  16. aiController: this.aiController
  17. }
  18. build() {
  19. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  20. Button('start')
  21. .width(100)
  22. .height(50)
  23. .margin(5)
  24. .onClick(() => {
  25. this.context.startImageAnalyzer(this.config)
  26. .then(() => {
  27. console.info("analysis complete")
  28. })
  29. .catch((error: BusinessError) => {
  30. let e: BusinessError = error as BusinessError
  31. console.error(`Error code: ${e.code}, message: ${e.message}`)
  32. })
  33. })
  34. Button('stop')
  35. .width(100)
  36. .height(50)
  37. .margin(5)
  38. .onClick(() => {
  39. this.context.stopImageAnalyzer()
  40. })
  41. Button('getTypes')
  42. .width(100)
  43. .height(50)
  44. .margin(5)
  45. .onClick(() => {
  46. this.aiController.getImageAnalyzerSupportTypes()
  47. })
  48. Canvas(this.context, this.options)
  49. .width(200)
  50. .height(200)
  51. .enableAnalyzer(true)
  52. .onReady(() => {
  53. this.context.drawImage(this.img, 0, 0, 200, 200)
  54. })
  55. }
  56. .width('100%')
  57. .height('100%')
  58. }
  59. }

getContext2DFromDrawingContext23+

Phone23+PC/2in123+Tablet23+TV23+Wearable23+

static getContext2DFromDrawingContext(drawingContext: DrawingRenderingContext, options?: RenderingContextOptions): CanvasRenderingContext2D

Obtains a CanvasRenderingContext2D object from a DrawingRenderingContext object. This CanvasRenderingContext2D object is bound to the same Canvas component as the input DrawingRenderingContext object.

NOTE
  • The CanvasRenderingContext2D object obtained via this API cannot be used as a parameter to create a Canvas component. Otherwise, the application crashes.

  • If the input DrawingRenderingContext object is not bound to a Canvas component, an error code is returned.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Model restriction: This API can be used only in the stage model.

Parameters

Expand
Name Type Mandatory Description
drawingContext DrawingRenderingContext Yes An object of the DrawingRenderingContext type.
options RenderingContextOptions No

Configuration options of the rendering context.

Default value: { antialias: false }

Return value

Expand
Type Description
CanvasRenderingContext2D Returns a CanvasRenderingContext2D object that is bound to the same Canvas component as the input DrawingRenderingContext.

Error codes

For details about the error codes, see Canvas Component Error Codes.

Expand
ID Error Message
103702 The drawingContext is not bound to a canvas component.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. import { LengthMetricsUnit } from '@kit.ArkUI';
  3. @Entry
  4. @Component
  5. struct CanvasExample {
  6. build() {
  7. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  8. Canvas({ unit: LengthMetricsUnit.DEFAULT })
  9. .onReady((drawingContext?: DrawingRenderingContext) => {
  10. if (!drawingContext) {
  11. return
  12. }
  13. let context2D: CanvasRenderingContext2D =
  14. CanvasRenderingContext2D.getContext2DFromDrawingContext(drawingContext, { antialias: true })
  15. context2D.fillStyle = 'rgb(39,135,217)'
  16. context2D.fillRect(10, 30, 100, 100)
  17. })
  18. }
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }

RenderingContextOptions23+

Phone23+PC/2in123+Tablet23+TV23+Wearable23+

Defines the specific configuration parameters for the rendering context.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Model restriction: This API can be used only in the stage model.

Expand
Name Type Read Only Optional Description
antialias boolean No Yes

Indicates whether to enable anti-aliasing for the RenderingContext.

A value of undefined is treated as the default value.

true: Enable anti-aliasing. false: Disable anti-aliasing.

Default value: false

CanvasDirection

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CanvasDirection = "inherit" | "ltr" | "rtl"

Defines the current text direction. The value type is a union of the types listed in the table below.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Description
inherit Inherits the text direction set in the general attributes of the canvas component. If the direction attribute is not set on the canvas component, the system text direction is used.
ltr The text direction is from left to right.
rtl The text direction is from right to left.

CanvasFillRule

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CanvasFillRule = "evenodd" | "nonzero"

Defines the fill pattern algorithm used to determine whether a point is inside or outside a path. The value type is a union of the types listed in the table below.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Description
evenodd

The inside part of a shape is determined based on whether the counting result is an odd number or not.

This rule determines whether a point is inside a shape by casting a ray from the point on the canvas in any direction and counting the number of intersections between the ray and the shape path. If the number of intersections is odd, the point is inside the shape. Otherwise, the point is outside the shape.

nonzero

The inside part of a shape is determined based on whether the counting result is zero or not.

This rule determines whether a point is inside a shape by casting a ray from the point on the canvas in any direction and checking the intersections between the ray and the shape path. The initial count is 0: assign a direction value to each segment of the path, add 1 each time the path crosses the ray from left to right, and subtract 1 each time it crosses the ray from right to left. If the final result is 0, the point is outside the shape. Otherwise, the point is inside the shape.

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Index {
  5. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  6. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  7. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  8. build() {
  9. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  10. Canvas(this.context)
  11. .width('100%')
  12. .height('100%')
  13. .backgroundColor('rgb(213, 213, 213)')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.font = '60px sans-serif'
  17. offContext.fillStyle = 'rgb(39, 135, 217)';
  18. // Non-zero rule (nonzero).
  19. offContext.beginPath();
  20. offContext.arc(100, 100, 60, 0, Math.PI * 2);
  21. offContext.arc(100, 100, 20, 0, Math.PI * 2);
  22. offContext.fill('nonzero'); // Use the non-zero rule.
  23. offContext.fillText('nonzero', 65, 200)
  24. // Even-odd rule (evenodd).
  25. offContext.beginPath();
  26. offContext.arc(250, 100, 60, 0, Math.PI * 2);
  27. offContext.arc(250, 100, 20, 0, Math.PI * 2);
  28. offContext.fill('evenodd'); // Use the even-odd rule.
  29. offContext.fillText('evenodd', 215, 200)
  30. let image = this.offCanvas.transferToImageBitmap()
  31. this.context.transferFromImageBitmap(image)
  32. })
  33. }
  34. .width('100%')
  35. .height('100%')
  36. }
  37. }

CanvasLineCap

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CanvasLineCap = "butt" | "round" | "square"

Defines the end caps for each line being drawn. The value type is a union of the types listed in the table below.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Description
butt The ends of the line are squared off, and the line does not extend beyond its two endpoints.
round The line is extended at the endpoints by a half circle whose diameter is equal to the line width.
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.

CanvasLineJoin

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CanvasLineJoin = "bevel" | "miter" | "round"

Defines the type of join between two non-zero-length segments (lines, arcs, and curves). The value type is a union of the types listed in the table below.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Description
bevel The intersection is a triangle. The rectangular corner of each line is independent.
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.
round The intersection is a sector, whose radius at the rounded corner is equal to the line width.

CanvasTextAlign

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CanvasTextAlign = "center" | "end" | "left" | "right" | "start"

Defines the type of text alignment. The value type is a union of the types listed in the table below.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Description
center The text is center-aligned.
start The text is aligned with the start bound.
end The text is aligned with the end bound.
left The text is left-aligned.
right The text is right-aligned.

CanvasTextBaseline

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CanvasTextBaseline = "alphabetic" | "bottom" | "hanging" | "ideographic" | "middle" | "top"

Defines the text baseline type. The value type is a union of the types listed in the table below.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Description
alphabetic The text baseline is the normal alphabetic baseline.
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.
hanging The text baseline is a hanging baseline over the text.
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.
middle The text baseline is in the middle of the text bounding box.
top The text baseline is on the top of the text bounding box.

ImageSmoothingQuality

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type ImageSmoothingQuality = "high" | "low" | "medium"

Defines the image smoothing quality. The value type is a union of the types listed in the table below.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Type Description
low Low quality.
medium Medium quality.
high High quality.

TextMetrics

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Name Type Read Only Optional Description
width number Yes No Width of the text. Read-only.
height number Yes No Height of the text. Read-only.
actualBoundingBoxAscent number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the top of the bounding rectangle used to render the text. Read-only.
actualBoundingBoxDescent number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the bounding rectangle used to render the text. Read-only.
actualBoundingBoxLeft number Yes No 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. Read-only.
actualBoundingBoxRight number Yes No 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. Read-only.
alphabeticBaseline number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the alphabetic baseline of the line box. Read-only.
emHeightAscent number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the top of the em square in the line box. Read-only.
emHeightDescent number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the em square in the line box. Read-only.
fontBoundingBoxAscent number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the top of the bounding rectangle of all the fonts used to render the text. Read-only.
fontBoundingBoxDescent number Yes No 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. Read-only.
hangingBaseline number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the hanging baseline of the line box. Read-only.
ideographicBaseline number Yes No Distance from the horizontal line specified by the CanvasRenderingContext2D.textBaseline attribute to the ideographic baseline of the line box. Read-only.

RenderingContextSettings

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

Configures the settings of a CanvasRenderingContext2D object, including whether to enable anti-aliasing.

constructor

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

constructor(antialias?: boolean)

Constructs a CanvasRenderingContext2D object. Anti-aliasing can be enabled.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
antialias boolean No

Whether to enable anti-aliasing.

A value of undefined is treated as the default value.

false: Disable anti-aliasing. true: Enable anti-aliasing.

Default value: false

NOTE

Anti-aliasing is enabled by default for text drawing. The antialias attribute of RenderingContextSettings does not affect the anti-aliasing effect of the drawn text. To adjust the anti-aliasing effect for text, use the antialias24+ API.

Attributes

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Expand
Name Type Read Only Optional Description
antialias boolean No Yes

Whether to enable anti-aliasing.

A value of undefined is treated as the default value.

false: Disable anti-aliasing. true: Enable anti-aliasing.

Default value: false

NOTE

Anti-aliasing is enabled by default for text drawing. The antialias attribute of RenderingContextSettings does not affect the anti-aliasing effect of the drawn text. To adjust the anti-aliasing effect for text, use the antialias24+ API.

Search in References
Enter a keyword.