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

Common Canvas Rendering Methods

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

Provides common drawing methods for the canvas drawing components CanvasRenderingContext2D and OffscreenCanvasRenderingContext2D.

NOTE
  • The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.

  • The following methods, when called in hidden pages, will generate caches. Avoid frequently refreshing the canvas in hidden pages.

fillRect

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

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

Fills a rectangle.

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 upper left corner of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is performed.

Default unit: vp

y number Yes

Y coordinate of the upper left corner of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is performed.

Default unit: vp

w number Yes

Width of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is performed.

Default unit: vp

h number Yes

Height of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is 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. 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.fillRect(30, 30, 100, 100)
  17. let image = this.offCanvas.transferToImageBitmap()
  18. this.context.transferFromImageBitmap(image)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

strokeRect

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

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

Draws a rectangle with a border, without filling the 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 upper left corner of the rectangle.

Abnormal values such as undefined, null, NaN, or Infinity are treated as invalid values and will not be drawn.

Default unit: vp

y number Yes

Y coordinate of the upper left corner of the rectangle.

Abnormal values such as undefined, null, NaN, or Infinity are treated as invalid values and will not be drawn.

Default unit: vp

w number Yes

Width of the rectangle.

Abnormal values such as undefined, null, NaN, or Infinity are treated as invalid values and will not be drawn.

Default unit: vp

h number Yes

Height of the rectangle.

Abnormal values such as undefined, null, NaN, or Infinity are treated as invalid values and will not be drawn.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.strokeRect(30, 30, 200, 150)
  17. let image = this.offCanvas.transferToImageBitmap()
  18. this.context.transferFromImageBitmap(image)
  19. })
  20. }
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }

clearRect

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

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

Clears the drawn content in the specified area.

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 upper left corner of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is performed.

Default unit: vp

y number Yes

Y coordinate of the upper left corner of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is performed.

Default unit: vp

w number Yes

Width of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is performed.

Default unit: vp

h number Yes

Height of the rectangle.

Abnormal values undefined, null, NaN, or Infinity are treated as invalid values and no drawing is 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.fillStyle = 'rgb(0,0,255)'
  17. offContext.fillRect(20, 20, 200, 200)
  18. offContext.clearRect(30, 30, 150, 100)
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

fillText

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

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

Draws filled text.

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 content to draw.

Anomalous values such as undefined or null are treated as invalid values, and no drawing is performed.

x number Yes

X-coordinate of the starting point for drawing the text.

Anomalous values such as undefined, null, NaN, or Infinity are treated as invalid values, and no drawing is performed.

Default unit: vp

y number Yes

Y-coordinate of the starting point for drawing the text.

Anomalous values such as undefined, null, NaN, or Infinity are treated as invalid values, and no drawing is performed.

Default unit: vp

maxWidth number No

Maximum width allowed for the text.

Anomalous value null is treated as an invalid value, and no drawing is performed. undefined, NaN, or Infinity are processed as default values.

Default unit: vp

Default value: no width limit.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.font = '30px sans-serif'
  17. offContext.fillText("Hello World!", 20, 100)
  18. let image = this.offCanvas.transferToImageBitmap()
  19. this.context.transferFromImageBitmap(image)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

strokeText

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

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

Draws stroked text.

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 content to draw.

If the value is undefined or null, it is treated as an invalid value and no drawing is performed.

x number Yes

X-coordinate of the starting point for text rendering.

If the value is undefined, null, NaN, or Infinity, it is treated as an invalid value and no drawing is performed.

Default unit: vp

y number Yes

Y-coordinate of the starting point for text rendering.

If the value is undefined, null, NaN, or Infinity, it is treated as an invalid value and no drawing is performed.

Default unit: vp

maxWidth number No

Maximum width of the text to draw.

If the value is null, it is treated as an invalid value and no drawing is performed. If the value is undefined, NaN, or Infinity, the default value is used.

Default unit: vp

Default value: no width limit

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.font = '55px sans-serif'
  17. offContext.strokeText("Hello World!", 20, 60)
  18. let image = this.offCanvas.transferToImageBitmap()
  19. this.context.transferFromImageBitmap(image)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

measureText

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

measureText(text: string): TextMetrics

Returns a text measurement object, through which the width of the specified text can be obtained.

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 be measured.

Return value

Expand
Type Description
TextMetrics

Text metrics.

If an invalid value (undefined or null) is passed in, the text is processed as "undefined" or "null".

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. 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 = '50px sans-serif'
  17. offContext.fillText("Hello World!", 20, 100)
  18. offContext.fillText("width:" + offContext.measureText("Hello World!").width, 20, 200)
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

stroke

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

stroke(): void

Performs a stroke operation based on 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

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 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.moveTo(125, 25)
  17. offContext.lineTo(125, 105)
  18. offContext.lineTo(175, 105)
  19. offContext.lineTo(175, 25)
  20. offContext.strokeStyle = 'rgb(255,0,0)'
  21. offContext.stroke()
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

stroke

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

stroke(path: Path2D): void

Performs stroke drawing based on the 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 to draw.

If an invalid value (undefined or null) is passed, no drawing 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 offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  8. private path2Da: Path2D = new Path2D();
  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 offContext = this.offCanvas.getContext("2d", this.settings)
  17. this.path2Da.moveTo(25, 25)
  18. this.path2Da.lineTo(25, 105)
  19. this.path2Da.lineTo(75, 105)
  20. this.path2Da.lineTo(75, 25)
  21. offContext.strokeStyle = 'rgb(0,0,255)'
  22. offContext.stroke(this.path2Da)
  23. let image = this.offCanvas.transferToImageBitmap()
  24. this.context.transferFromImageBitmap(image)
  25. })
  26. }
  27. .width('100%')
  28. .height('100%')
  29. }
  30. }

beginPath

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

beginPath(): void

Creates a new 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. 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.beginPath()
  17. offContext.lineWidth = 6
  18. offContext.strokeStyle = '#0000ff'
  19. offContext.moveTo(15, 80)
  20. offContext.lineTo(280, 160)
  21. offContext.stroke()
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

moveTo

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

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

Moves the path from the current point to a specified point.

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, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. In API version 18 and later, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y number Yes

Y coordinate of the target position.

In versions earlier than API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. In API version 18 and later, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

NOTE

In versions earlier than API version 18, if the moveTo API is not executed or the moveTo API passes invalid parameters, the path starts with (0,0).

In API version 18 and later, if the moveTo API is not executed or the moveTo API passes invalid parameters, the path starts from the start point of the lineTo, arcTo, bezierCurveTo, or quadraticCurveTo API that is called for the first time.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.beginPath()
  17. offContext.moveTo(10, 10)
  18. offContext.lineTo(280, 160)
  19. offContext.stroke()
  20. let image = this.offCanvas.transferToImageBitmap()
  21. this.context.transferFromImageBitmap(image)
  22. })
  23. }
  24. .width('100%')
  25. .height('100%')
  26. }
  27. }

lineTo

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

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

Connects the current point to a specified point by a 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
x number Yes

X coordinate of the target position.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when it is set to null or undefined, the current API does not take effect. From API version 18 onward, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y number Yes

Y coordinate of the target position.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when it is set to null or undefined, the current API does not take effect. From API version 18 onward, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.beginPath()
  17. offContext.moveTo(10, 10)
  18. offContext.lineTo(280, 160)
  19. offContext.stroke()
  20. let image = this.offCanvas.transferToImageBitmap()
  21. this.context.transferFromImageBitmap(image)
  22. })
  23. }
  24. .width('100%')
  25. .height('100%')
  26. }
  27. }

closePath

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

closePath(): void

Closes the current path to form 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.beginPath()
  17. offContext.moveTo(30, 30)
  18. offContext.lineTo(110, 30)
  19. offContext.lineTo(70, 90)
  20. offContext.closePath()
  21. offContext.stroke()
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

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

Image source object. For details, see ImageBitmap.

An invalid value, such as undefined or null, is processed as an invalid value.

repetition string | null Yes

Image repetition mode:

'repeat': repeats the image along both the x-axis and y-axis;

'repeat-x': repeats the image along the x-axis;

'repeat-y': repeats the image along the y-axis;

'no-repeat': does not repeat the image;

'clamp': uses the edge color for the part that exceeds the original boundary when drawing outside it;

'mirror': repeats and flips the image along both the x-axis and y-axis.

An invalid value, such as undefined or null, is processed as an invalid value.

Return value

Expand
Type Description
CanvasPattern | null Pattern object created by specifying an 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 > resOptions > copyCodeResource in the module's build-profile.json5 file, 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/example.jpg" with the image resource file required by the developer.
  8. private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  10. build() {
  11. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  12. Canvas(this.context)
  13. .width('100%')
  14. .height('100%')
  15. .backgroundColor('rgb(213,213,213)')
  16. .onReady(() => {
  17. let offContext = this.offCanvas.getContext("2d", this.settings)
  18. let pattern = offContext.createPattern(this.img, 'repeat')
  19. offContext.fillStyle = pattern as CanvasPattern
  20. offContext.fillRect(0, 0, 200, 200)
  21. let image = this.offCanvas.transferToImageBitmap()
  22. this.context.transferFromImageBitmap(image)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

bezierCurveTo

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

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

Creates a cubic Bezier curve 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
cp1x number Yes

X-coordinate of the first Bezier parameter.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, this API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

cp1y number Yes

Y-coordinate of the first Bezier parameter.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, this API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

cp2x number Yes

X-coordinate of the second Bezier parameter.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, this API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

cp2y number Yes

Y-coordinate of the second Bezier parameter.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, this API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

x number Yes

X-coordinate of the end point of the path.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, this API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y number Yes

Y-coordinate of the end point of the path.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, this API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other path methods with valid parameters are drawn normally.

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 offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  9. private start: Point = { x: 50, y: 50 };
  10. private end: Point = { x: 250, y: 100 };
  11. private cp1: Point = { x: 200, y: 30 };
  12. private cp2: Point = { x: 130, y: 80 };
  13. build() {
  14. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  15. Canvas(this.context)
  16. .width('100%')
  17. .height('100%')
  18. .backgroundColor('rgb(213,213,213)')
  19. .onReady(() => {
  20. let offContext = this.offCanvas.getContext("2d", this.settings)
  21. // Cubic Bezier curve
  22. offContext.beginPath();
  23. offContext.moveTo(this.start.x, this.start.y);
  24. offContext.bezierCurveTo(this.cp1.x, this.cp1.y, this.cp2.x, this.cp2.y, this.end.x, this.end.y);
  25. offContext.stroke();
  26. // Start point and end point
  27. offContext.fillStyle = 'rgb(39,135,217)';
  28. offContext.beginPath();
  29. offContext.arc(this.start.x, this.start.y, 5, 0, 2 * Math.PI); // Start point
  30. offContext.arc(this.end.x, this.end.y, 5, 0, 2 * Math.PI); // End point
  31. offContext.fill();
  32. // Control points
  33. offContext.fillStyle = 'rgb(23,169,141)';
  34. offContext.beginPath();
  35. offContext.arc(this.cp1.x, this.cp1.y, 5, 0, 2 * Math.PI); // Control point 1.
  36. offContext.arc(this.cp2.x, this.cp2.y, 5, 0, 2 * Math.PI); // Control point 2.
  37. offContext.fill();
  38. let image = this.offCanvas.transferToImageBitmap();
  39. this.context.transferFromImageBitmap(image);
  40. })
  41. }
  42. .width('100%')
  43. .height('100%')
  44. }
  45. }

quadraticCurveTo

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

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

Creates a quadratic Bezier curve 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
cpx number Yes

X-coordinate of the Bezier parameter.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, the current API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

cpy number Yes

Y-coordinate of the Bezier parameter.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, the current API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

x number Yes

X-coordinate of the end point of the path.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, the current API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y number Yes

Y-coordinate of the end point of the path.

Before API version 18, if NaN or Infinity is set, the entire path is not displayed; if null or undefined is set, the current API does not take effect. Since API version 18, if NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

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 offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  9. private start: Point = { x: 50, y: 20 };
  10. private end: Point = { x: 50, y: 100 };
  11. private cp: Point = { x: 230, y: 30 };
  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 offContext = this.offCanvas.getContext("2d", this.settings);
  20. // Quadratic Bezier curve
  21. offContext.beginPath();
  22. offContext.moveTo(this.start.x, this.start.y);
  23. offContext.quadraticCurveTo(this.cp.x, this.cp.y, this.end.x, this.end.y);
  24. offContext.stroke();
  25. // Start point and end point
  26. offContext.fillStyle = 'rgb(39,135,217)';
  27. offContext.beginPath();
  28. offContext.arc(this.start.x, this.start.y, 5, 0, 2 * Math.PI); // Start point
  29. offContext.arc(this.end.x, this.end.y, 5, 0, 2 * Math.PI); // End point
  30. offContext.fill();
  31. // Control point
  32. offContext.fillStyle = 'rgb(23,169,141)';
  33. offContext.beginPath();
  34. offContext.arc(this.cp.x, this.cp.y, 5, 0, 2 * Math.PI);
  35. offContext.fill();
  36. let image = this.offCanvas.transferToImageBitmap();
  37. this.context.transferFromImageBitmap(image);
  38. })
  39. }
  40. .width('100%')
  41. .height('100%')
  42. }
  43. }

arc

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

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

Draws an arc 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
x number Yes

X-coordinate of the arc center.

Before API version 18, if this parameter is set to NaN or Infinity, the entire path is not displayed; if it is set to null or undefined, the current API does not take effect. Since API version 18, if this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y number Yes

Y-coordinate of the arc center.

Before API version 18, if this parameter is set to NaN or Infinity, the entire path is not displayed; if it is set to null or undefined, the current API does not take effect. Since API version 18, if this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

radius number Yes

Radius of the arc.

Before API version 18, if this parameter is set to NaN or Infinity, the entire path is not displayed; if it is set to null or undefined, the current API does not take effect. Since API version 18, if this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

startAngle number Yes

Start angle of the arc.

Before API version 18, if this parameter is set to NaN or Infinity, the entire path is not displayed; if it is set to null or undefined, the current API does not take effect. Since API version 18, if this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: radian

endAngle number Yes

End angle of the arc.

Before API version 18, if this parameter is set to NaN or Infinity, the entire path is not displayed; if it is set to null or undefined, the current API does not take effect. Since API version 18, if this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: radian

counterclockwise boolean No

Whether to draw the arc counterclockwise.

The value true means to draw the arc counterclockwise, and false means to draw the arc clockwise.

Default value: 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.beginPath()
  17. offContext.arc(100, 75, 50, 0, 6.28)
  18. offContext.stroke()
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

arcTo

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

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

Creates an arc path based on the given control points and arc 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.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when set to null or undefined, the current API does not take effect. From API version 18 onward, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y1 number Yes

Y coordinate of the first control point.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when set to null or undefined, the current API does not take effect. From API version 18 onward, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

x2 number Yes

X coordinate of the second control point.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when set to null or undefined, the current API does not take effect. From API version 18 onward, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y2 number Yes

Y coordinate of the second control point.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when set to null or undefined, the current API does not take effect. From API version 18 onward, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

radius number Yes

Radius of the arc.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when set to null or undefined, the current API does not take effect. From API version 18 onward, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. // Tangent line
  17. offContext.beginPath()
  18. offContext.strokeStyle = '#808080'
  19. offContext.lineWidth = 1.5;
  20. offContext.moveTo(360, 20);
  21. offContext.lineTo(360, 170);
  22. offContext.lineTo(110, 170);
  23. offContext.stroke();
  24. // Arc
  25. offContext.beginPath()
  26. offContext.strokeStyle = '#000000'
  27. offContext.lineWidth = 3;
  28. offContext.moveTo(360, 20)
  29. offContext.arcTo(360, 170, 110, 170, 150)
  30. offContext.stroke()
  31. // Start point
  32. offContext.beginPath();
  33. offContext.fillStyle = '#00ff00';
  34. offContext.arc(360, 20, 4, 0, 2 * Math.PI);
  35. offContext.fill();
  36. // Control point
  37. offContext.beginPath();
  38. offContext.fillStyle = '#ff0000';
  39. offContext.arc(360, 170, 4, 0, 2 * Math.PI);
  40. offContext.arc(110, 170, 4, 0, 2 * Math.PI);
  41. offContext.fill();
  42. let image = this.offCanvas.transferToImageBitmap()
  43. this.context.transferFromImageBitmap(image)
  44. })
  45. }
  46. .width('100%')
  47. .height('100%')
  48. }
  49. }

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

Imagine two tangents: one from the start point to the first control point, and the other from the first control point to the second control point. arcTo() creates an arc between these two tangents, and the arc is tangent to both.

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

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.

Before API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y number Yes

Y-coordinate of the ellipse center.

Before API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

radiusX number Yes

Radius of the ellipse on the x-axis.

Before API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

radiusY number Yes

Radius of the ellipse on the y-axis.

Before API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

rotation number Yes

Rotation angle of the ellipse.

Before API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Unit: radian.

startAngle number Yes

Start angle of the ellipse.

Before API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Unit: radian.

endAngle number Yes

End angle of the ellipse.

Before API version 18, when NaN or Infinity is set, the entire path is not displayed; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Unit: radian.

counterclockwise boolean No

Whether to draw the ellipse in the counterclockwise direction.

true: draws the ellipse in the counterclockwise direction.

false: draws the ellipse in the clockwise direction.

Default value: false. If null or undefined is set, 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.beginPath()
  17. offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2, false)
  18. offContext.stroke()
  19. offContext.beginPath()
  20. offContext.ellipse(200, 300, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2, true)
  21. offContext.stroke()
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

rect

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

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

Creates a rectangle 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
x number Yes

X coordinate of the upper left corner of the rectangle.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when it is set to null or undefined, the current API does not take effect. Since API version 18, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

y number Yes

Y coordinate of the upper left corner of the rectangle.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when it is set to null or undefined, the current API does not take effect. Since API version 18, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

w number Yes

Width of the rectangle.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when it is set to null or undefined, the current API does not take effect. Since API version 18, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

Default unit: vp

h number Yes

Height of the rectangle.

Before API version 18, when this parameter is set to NaN or Infinity, the entire path is not displayed; when it is set to null or undefined, the current API does not take effect. Since API version 18, when this parameter is set to NaN, Infinity, null, or undefined, the current API does not take effect, and other path methods with valid parameters are drawn normally.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
  17. offContext.stroke()
  18. let image = this.offCanvas.transferToImageBitmap()
  19. this.context.transferFromImageBitmap(image)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

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 method does not directly draw the content. To draw a rounded rectangle on the canvas, use the fill or stroke method.

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.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
x number Yes

X-coordinate of the upper left corner of the rectangle.

null is processed as 0, and undefined is processed as an invalid value, in which case nothing is drawn.

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

Default unit: vp

y number Yes

Y-coordinate of the upper left corner of the rectangle.

null is processed as 0, and undefined is processed as an invalid value, in which case nothing is drawn.

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 means drawing to the left.

null is processed as 0, and undefined is processed as an invalid value, in which case nothing is drawn.

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 means drawing upward.

null is processed as 0, and undefined is processed as an invalid value, in which case nothing is drawn.

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

Default unit: vp

radii number | Array<number> No

Number or a list of numbers for the arc radii of the rectangle corners.

When the parameter type is number, the arc radius of all rectangle corners follows this number.

When the parameter type is Array<number>, the number of elements ranges from 1 to 4, processed as follows:

1. [arc radius of all rectangle corners]

2. [arc radius of the upper left and lower right corners, arc radius of the upper right and lower left corners]

3. [arc radius of the upper left corner, arc radius of the upper right and lower left corners, arc radius of the lower right corner]

4. [arc radius of the upper left corner, arc radius of the upper right corner, arc radius of the lower right corner, arc radius of the lower left corner]

An exception is thrown if radii contains a negative value or the number of elements in the list is not within [1, 4]. Error code: 103701.

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

If the arc radius exceeds the width or height of the rectangle, it is scaled down proportionally to the length of the width or height.

Default unit: vp

Error codes

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

Expand
ID Error Message Possible Cause
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

This example shows how to draw the following rounded rectangles.

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

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

  3. Create a rounded rectangle with the start point (10 vp, 120 vp), width and height of 100 vp, and the radius of the upper-left and lower-right rounded corners of 10 vp, and the radius of the upper-right and lower-left rounded corners of 20 vp. The rounded rectangle is outlined.

  4. Create a rounded rectangle with the start point (120 vp, 120 vp), width and height of 100 vp, and the radius of the upper-left rounded corner of 10 vp, the radius of the upper-right and lower-left rounded corners of 20 vp, and the radius of the lower-right rounded corner of 30 vp. The rounded rectangle is outlined.

  5. Create a rounded rectangle with the start point (10 vp, 230 vp), width and height of 100 vp, and the radius of the upper-left rounded corner of 10 vp, the radius of the upper-right rounded corner of 20 vp, the radius of the lower-right rounded corner of 30 vp, and the radius of the lower-left rounded corner of 40 vp. The rounded rectangle is outlined.

  6. Create a rounded rectangle with the start point (220 vp, 330 vp), width and height of -100 vp, and the radius of the upper-left rounded corner of 10 vp, the radius of the upper-right rounded corner of 20 vp, the radius of the lower-right rounded corner of 30 vp, and the radius of the lower-left rounded corner of 40 vp. The rounded rectangle is outlined.

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. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  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. let offContext = this.offCanvas.getContext("2d", this.settings)
  17. try {
  18. offContext.fillStyle = '#707070'
  19. offContext.beginPath()
  20. // Create a rounded rectangle with (10 vp, 10 vp) as the starting point, a width and height of 100 vp, and a corner radius of 10 vp for all four corners.
  21. offContext.roundRect(10, 10, 100, 100, 10)
  22. // Create a rounded rectangle with (120 vp, 10 vp) as the starting point, a width and height of 100 vp, and a corner radius of 10 vp for all four corners.
  23. offContext.roundRect(120, 10, 100, 100, [10])
  24. offContext.fill()
  25. offContext.beginPath()
  26. // Create a rounded rectangle with (10 vp, 120 vp) as the starting point, a width and height of 100 vp, a top-left and bottom-right corner radius of 10 vp, and a top-right and bottom-left corner radius of 20 vp.
  27. offContext.roundRect(10, 120, 100, 100, [10, 20])
  28. // Create a rounded rectangle with (120 vp, 120 vp) as the starting point, a width and height of 100 vp, a top-left corner radius of 10 vp, a top-right and bottom-left corner radius of 20 vp, and a bottom-right corner radius of 30 vp.
  29. offContext.roundRect(120, 120, 100, 100, [10, 20, 30])
  30. // Create a rounded rectangle with (10 vp, 230 vp) as the starting point, width and height of 100 vp, top-left corner radius of 10 vp, top-right corner radius of 20 vp, bottom-right corner radius of 30 vp, and bottom-left corner radius of 40vp.
  31. offContext.roundRect(10, 230, 100, 100, [10, 20, 30, 40])
  32. // Create a rounded rectangle with (220 vp, 330 vp) as the starting point, width and height of -100 vp, top-left corner radius of 10 vp, top-right corner radius of 20 vp, bottom-right corner radius of 30 vp, and bottom-left corner radius of 40vp.
  33. offContext.roundRect(220, 330, -100, -100, [10, 20, 30, 40])
  34. offContext.stroke()
  35. } catch (error) {
  36. let e: BusinessError = error as BusinessError;
  37. console.error(`Failed to create roundRect. Code: ${e.code}, message: ${e.message}`);
  38. }
  39. // Create an ImageBitmap object from the most recently drawn image on the offscreen canvas.
  40. let image = this.offCanvas.transferToImageBitmap()
  41. // Display the created ImageBitmap object on the Canvas.
  42. this.context.transferFromImageBitmap(image)
  43. })
  44. }
  45. .width('100%')
  46. .height('100%')
  47. }
  48. }

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 for filling the object.

The options are "nonzero" and "evenodd".

Abnormal values undefined or null are processed as the default value.

Default value: "nonzero"

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.fillStyle = '#000000'
  17. offContext.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20)
  18. offContext.fill()
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

fill

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

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

Fills the 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 fill path.

Anomalous values undefined or null are treated as invalid.

fillRule CanvasFillRule No

Rule for filling the object.

Optional values: "nonzero" and "evenodd".

Anomalous values undefined or null are treated as the default.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. let region = new Path2D()
  17. region.moveTo(30, 90)
  18. region.lineTo(110, 20)
  19. region.lineTo(240, 130)
  20. region.lineTo(60, 130)
  21. region.lineTo(190, 20)
  22. region.lineTo(270, 90)
  23. region.closePath()
  24. // Fill path
  25. offContext.fillStyle = '#00ff00'
  26. offContext.fill(region, "evenodd")
  27. let image = this.offCanvas.transferToImageBitmap()
  28. this.context.transferFromImageBitmap(image)
  29. })
  30. }
  31. .width('100%')
  32. .height('100%')
  33. }
  34. }

clip

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

clip(fillRule?: CanvasFillRule): void

Sets the current 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
fillRule CanvasFillRule No

Rule for the object to be clipped.

Optional values: "nonzero", "evenodd".

Abnormal values undefined or null are processed 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.rect(0, 0, 100, 200)
  17. offContext.stroke()
  18. offContext.clip()
  19. offContext.fillStyle = "rgb(255,0,0)"
  20. offContext.fillRect(0, 0, 200, 200)
  21. let image = this.offCanvas.transferToImageBitmap()
  22. this.context.transferFromImageBitmap(image)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

clip

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

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

Sets the 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 clipping path.

Abnormal values such as undefined or null are treated as invalid values.

fillRule CanvasFillRule No

Rule for clipping objects.

Optional values: "nonzero" and "evenodd".

Abnormal values such as undefined or null are processed based on 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. let region = new Path2D()
  17. region.moveTo(30, 90)
  18. region.lineTo(110, 20)
  19. region.lineTo(240, 130)
  20. region.lineTo(60, 130)
  21. region.lineTo(190, 20)
  22. region.lineTo(270, 90)
  23. region.closePath()
  24. offContext.clip(region,"evenodd")
  25. offContext.fillStyle = "rgb(0,255,0)"
  26. offContext.fillRect(0, 0, 600, 600)
  27. let image = this.offCanvas.transferToImageBitmap()
  28. this.context.transferFromImageBitmap(image)
  29. })
  30. }
  31. .width('100%')
  32. .height('100%')
  33. }
  34. }

reset12+

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

reset(): void

Resets the OffscreenCanvasRenderingContext2D to its default state, clearing the back buffer, drawing state stack, drawing path, and styles.

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

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

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.fillStyle = '#0000ff'
  17. offContext.fillRect(20, 20, 150, 100)
  18. offContext.reset()
  19. offContext.fillRect(20, 150, 150, 100)
  20. let image = this.offCanvas.transferToImageBitmap()
  21. this.context.transferFromImageBitmap(image)
  22. })
  23. }
  24. .width('100%')
  25. .height('100%')
  26. }
  27. }

saveLayer12+

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

saveLayer(): void

Creates a layer.

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

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

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.fillStyle = "#0000ff"
  17. offContext.fillRect(50, 100, 300, 100)
  18. offContext.fillStyle = "#00ffff"
  19. offContext.fillRect(50, 150, 300, 100)
  20. offContext.globalCompositeOperation = 'destination-over'
  21. offContext.saveLayer()
  22. offContext.globalCompositeOperation = 'source-over'
  23. offContext.fillStyle = "#ff0000"
  24. offContext.fillRect(100, 50, 100, 300)
  25. offContext.fillStyle = "#00ff00"
  26. offContext.fillRect(150, 50, 100, 300)
  27. offContext.restoreLayer()
  28. let image = this.offCanvas.transferToImageBitmap()
  29. this.context.transferFromImageBitmap(image)
  30. })
  31. }
  32. .width('100%')
  33. .height('100%')
  34. }
  35. }

restoreLayer12+

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

restoreLayer(): void

Restores the image transform and clipping state to the state before saveLayer, and draws the layer on the canvas. The example for restoreLayer is the same as that for saveLayer.

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

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

System capability: SystemCapability.ArkUI.ArkUI.Full

resetTransform

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

resetTransform(): void

Resets the current matrix 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.setTransform(1,0.5, -0.5, 1, 10, 10)
  17. offContext.fillStyle = 'rgb(0,0,255)'
  18. offContext.fillRect(0, 0, 100, 100)
  19. offContext.resetTransform()
  20. offContext.fillStyle = 'rgb(255,0,0)'
  21. offContext.fillRect(0, 0, 100, 100)
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

rotate

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

rotate(angle: number): void

Rotates the current coordinate axes clockwise.

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

Radian value for clockwise rotation. You can convert an angle to a radian value using degree × Math.PI/180.

Before API version 18, when NaN or Infinity is set, drawing methods executed after this method cannot draw; when null or undefined is set, the current API does not take effect. From API version 18 onward, when NaN, Infinity, null, or undefined is set, the current API does not take effect, and other drawing methods with valid parameters draw normally.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.rotate(45 * Math.PI / 180)
  17. offContext.fillRect(70, 20, 50, 50)
  18. let image = this.offCanvas.transferToImageBitmap()
  19. this.context.transferFromImageBitmap(image)
  20. })
  21. }
  22. .width('100%')
  23. .height('100%')
  24. }
  25. }

scale

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

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

Sets the scaling transformation property of the canvas. Subsequent drawing operations are scaled according to the scaling ratio.

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.

Before API version 18, if NaN or Infinity is set, drawing methods executed after this method cannot draw; if null or undefined is set, the current API does not take effect. From API version 18 onward, if NaN, Infinity, null, or undefined is set, the current API does not take effect, and other drawing methods with valid parameters draw normally.

y number Yes

Vertical scale factor.

Before API version 18, if NaN or Infinity is set, drawing methods executed after this method cannot draw; if null or undefined is set, the current API does not take effect. From API version 18 onward, if NaN, Infinity, null, or undefined is set, the current API does not take effect, and other drawing methods with valid parameters draw normally.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.lineWidth = 3
  17. offContext.strokeRect(30, 30, 50, 50)
  18. offContext.scale(2, 2) // Scale to 200%
  19. offContext.strokeRect(30, 30, 50, 50)
  20. let image = this.offCanvas.transferToImageBitmap()
  21. this.context.transferFromImageBitmap(image)
  22. })
  23. }
  24. .width('100%')
  25. .height('100%')
  26. }
  27. }

transform

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

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

Corresponds to a transformation matrix. When you want to transform a shape, simply set the corresponding parameters of this transformation matrix, multiply the coordinates of each vertex of the shape by this matrix, and you can obtain the new vertex coordinates. Matrix transformation effects can be superimposed.

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 transformed coordinates of each point in the figure can be calculated using the following coordinate calculation formulas.

The transformed coordinates are calculated as follows (where x and y are the coordinates before transformation, and x' and y' are the 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: specifies the horizontal scaling value. Negative numbers are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

b number Yes

skewY: specifies the vertical skew value. Negative numbers are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

c number Yes

skewX: specifies the horizontal skew value. Negative numbers are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

d number Yes

scaleY: specifies the vertical scaling value. Negative numbers are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

e number Yes

translateX: specifies the horizontal translation value. Negative numbers are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

Default unit: vp

f number Yes

translateY: specifies the vertical translation value. Negative numbers are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

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. 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.fillStyle = 'rgb(112,112,112)'
  17. offContext.fillRect(0, 0, 100, 100)
  18. offContext.transform(1, 0.5, -0.5, 1, 10, 10)
  19. offContext.fillStyle = 'rgb(0,74,175)'
  20. offContext.fillRect(0, 0, 100, 100)
  21. offContext.transform(1, 0.5, -0.5, 1, 10, 10)
  22. offContext.fillStyle = 'rgb(39,135,217)'
  23. offContext.fillRect(0, 0, 100, 100)
  24. let image = this.offCanvas.transferToImageBitmap()
  25. this.context.transferFromImageBitmap(image)
  26. })
  27. }
  28. .width('100%')
  29. .height('100%')
  30. }
  31. }

setTransform

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

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

The setTransform method uses the same parameters as the transform() method, but the setTransform() method resets the existing transformation matrix and creates a new one.

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 transformed coordinates of each point in the graphic can be calculated using the following formulas.

The transformed coordinates are calculated as follows (where x and y are the original coordinates, and x' and y' are the transformed coordinates):

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

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

Parameters

Expand
Name Type Mandatory Description
a number Yes

scaleX: specifies the horizontal scale. Negative values are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

b number Yes

skewY: specifies the vertical skew. Negative values are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

c number Yes

skewX: specifies the horizontal skew. Negative values are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

d number Yes

scaleY: specifies the vertical scale. Negative values are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

e number Yes

translateX: specifies the horizontal translation. Negative values are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

Default unit: vp

f number Yes

translateY: specifies the vertical translation. Negative values are supported.

Before API version 18, if this parameter is set to NaN or Infinity, drawing methods executed after this method cannot draw. If it is set to null or undefined, this API does not take effect. From API version 18 onward, if this parameter is set to NaN, Infinity, null, or undefined, this API does not take effect, and other drawing methods with valid parameters can draw normally.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.fillStyle = 'rgb(255,0,0)'
  17. offContext.fillRect(0, 0, 100, 100)
  18. offContext.setTransform(1,0.5, -0.5, 1, 10, 10)
  19. offContext.fillStyle = 'rgb(0,0,255)'
  20. offContext.fillRect(0, 0, 100, 100)
  21. let image = this.offCanvas.transferToImageBitmap()
  22. this.context.transferFromImageBitmap(image)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

setTransform

setTransform(transform?: Matrix2D): void

Resets the existing transform matrix and creates a new one with the Matrix2D object as a template.

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.

Exception values 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 offcontext1: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 200, this.settings);
  8. private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  9. private offcontext2: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 200, this.settings);
  10. build() {
  11. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  12. Text('context1');
  13. Canvas(this.context1)
  14. .width('230vp')
  15. .height('160vp')
  16. .backgroundColor('#ffff00')
  17. .onReady(() => {
  18. this.offcontext1.fillRect(100, 20, 50, 50);
  19. this.offcontext1.setTransform(1, 0.5, -0.5, 1, 10, 10);
  20. this.offcontext1.fillRect(100, 20, 50, 50);
  21. let image = this.offcontext1.transferToImageBitmap();
  22. this.context1.transferFromImageBitmap(image);
  23. })
  24. Text('context2');
  25. Canvas(this.context2)
  26. .width('230vp')
  27. .height('160vp')
  28. .backgroundColor('#0ffff0')
  29. .onReady(() => {
  30. this.offcontext2.fillRect(100, 20, 50, 50);
  31. let storedTransform = this.offcontext1.getTransform();
  32. this.offcontext2.setTransform(storedTransform);
  33. this.offcontext2.fillRect(100, 20, 50, 50);
  34. let image = this.offcontext2.transferToImageBitmap();
  35. this.context2.transferFromImageBitmap(image);
  36. })
  37. }
  38. .width('100%')
  39. .height('100%')
  40. }
  41. }

getTransform

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

getTransform(): Matrix2D

Obtains the transform matrix currently 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 The transformation matrix currently 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 offcontext1: OffscreenCanvasRenderingContext2D =
  8. new OffscreenCanvasRenderingContext2D(600, 100, this.settings);
  9. private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  10. private offcontext2: OffscreenCanvasRenderingContext2D =
  11. new OffscreenCanvasRenderingContext2D(600, 100, this.settings);
  12. build() {
  13. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  14. Text('context1');
  15. Canvas(this.context1)
  16. .width('230vp')
  17. .height('120vp')
  18. .backgroundColor('#ffff00')
  19. .onReady(() => {
  20. this.offcontext1.fillRect(50, 50, 50, 50);
  21. this.offcontext1.setTransform(1.2, Math.PI / 8, Math.PI / 6, 0.5, 30, -25);
  22. this.offcontext1.fillRect(50, 50, 50, 50);
  23. let image = this.offcontext1.transferToImageBitmap();
  24. this.context1.transferFromImageBitmap(image);
  25. })
  26. Text('context2');
  27. Canvas(this.context2)
  28. .width('230vp')
  29. .height('120vp')
  30. .backgroundColor('#0ffff0')
  31. .onReady(() => {
  32. this.offcontext2.fillRect(50, 50, 50, 50);
  33. let storedTransform = this.offcontext1.getTransform();
  34. console.info(`Matrix [scaleX = ${storedTransform.scaleX}, scaleY = ${storedTransform.scaleY}, rotateX = ${storedTransform.rotateX}, rotateY = ${storedTransform.rotateY}, translateX = ${storedTransform.translateX}, translateY = ${storedTransform.translateY}]`)
  35. this.offcontext2.setTransform(storedTransform);
  36. this.offcontext2.fillRect(50, 50, 50, 50);
  37. let image = this.offcontext2.transferToImageBitmap();
  38. this.context2.transferFromImageBitmap(image);
  39. })
  40. }
  41. .width('100%')
  42. .height('100%')
  43. }
  44. }

translate

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

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

Moves the origin of the current 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

Horizontal translation amount.

Before API version 18, if NaN or Infinity is set, drawing methods executed after this method cannot draw; if null or undefined is set, this API does not take effect. From API version 18 onward, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other drawing methods with valid parameters draw normally.

Default unit: vp

y number Yes

Vertical translation amount.

Before API version 18, if NaN or Infinity is set, drawing methods executed after this method cannot draw; if null or undefined is set, this API does not take effect. From API version 18 onward, if NaN, Infinity, null, or undefined is set, this API does not take effect, and other drawing methods with valid parameters draw normally.

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.fillRect(10, 10, 50, 50)
  17. offContext.translate(70, 70)
  18. offContext.fillRect(10, 10, 50, 50)
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

drawImage

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

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

Draws an image.

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

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.

Anomalous values such as undefined or null are treated as invalid and no drawing is performed.

dx number Yes

X-coordinate of the upper left corner of the drawing area.

Anomalous values such as undefined or null are treated as 0, and NaN and Infinity are treated as invalid, in which case no drawing is performed.

Default unit: vp

dy number Yes

Y-coordinate of the upper left corner of the drawing area.

Anomalous values such as undefined or null are treated as 0, and NaN and Infinity are treated as invalid, in which case no drawing is 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 > resOptions > copyCodeResource in the module's build-profile.json5 file, 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 DrawImage {
  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 required by the developer.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  10. build() {
  11. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  12. Canvas(this.context)
  13. .width('100%')
  14. .height('100%')
  15. .backgroundColor('#D5D5D5')
  16. .onReady(() => {
  17. let offContext = this.offCanvas.getContext("2d", this.settings)
  18. offContext.drawImage(this.img, 0, 0)
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

drawImage

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

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

Draws the image by stretching or compressing it.

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

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.

Abnormal values undefined or null are treated as invalid and not drawn.

dx number Yes

X-axis position of the upper left corner of the drawing area.

Abnormal values undefined or null are treated as 0. NaN and Infinity are treated as invalid and not drawn.

Default unit: vp

dy number Yes

Y-axis position of the upper left corner of the drawing area.

Abnormal values undefined or null are treated as 0. NaN and Infinity are treated as invalid and not drawn.

Default unit: vp

dw number Yes

Width of the drawing area.

Negative values and abnormal values undefined or null are treated as 0. NaN and Infinity are treated as invalid and not drawn.

Default unit: vp

dh number Yes

Height of the drawing area.

Negative values and abnormal values undefined or null are treated as 0. NaN and Infinity are treated as invalid and not drawn.

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 > resOptions > copyCodeResource in the module's build-profile.json5 file, 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 DrawImage {
  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 required by the developer.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  10. build() {
  11. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  12. Canvas(this.context)
  13. .width('100%')
  14. .height('100%')
  15. .backgroundColor('#D5D5D5')
  16. .onReady(() => {
  17. let offContext = this.offCanvas.getContext("2d", this.settings)
  18. offContext.drawImage(this.img, 0, 0, 300, 300)
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

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 the image after cropping, stretching, or compressing it.

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

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.

Abnormal values undefined or null are treated as invalid and no drawing is performed.

sx number Yes

X-coordinate relative to the upper-left corner of the source image when cropping.

Abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is performed.

When image is of the ImageBitmap type, default unit: vp.

When image is of the PixelMap type, before API version 18, default unit: px; from API version 18 onward, default unit: vp.

sy number Yes

Y-coordinate relative to the upper-left corner of the source image when cropping.

Abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is performed.

When image is of the ImageBitmap type, default unit: vp.

When image is of the PixelMap type, before API version 18, default unit: px; from API version 18 onward, default unit: vp.

sw number Yes

Width to crop from the source image.

Negative values and abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is performed.

When image is of the ImageBitmap type, default unit: vp.

When image is of the PixelMap type, before API version 18, default unit: px; from API version 18 onward, default unit: vp.

sh number Yes

Height to crop from the source image.

Negative values and abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is performed.

When image is of the ImageBitmap type, default unit: vp.

When image is of the PixelMap type, before API version 18, default unit: px; from API version 18 onward, default unit: vp.

dx number Yes

X-coordinate of the upper-left corner of the drawing area.

Abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is performed.

Default unit: vp.

dy number Yes

Y-coordinate of the upper-left corner of the drawing area.

Abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is performed.

Default unit: vp.

dw number Yes

Width of the drawing area.

Negative values and abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is performed.

Default unit: vp.

dh number Yes

Height of the drawing area.

Negative values and abnormal values undefined or null are treated as 0; NaN and Infinity are treated as invalid and no drawing is 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 > resOptions > copyCodeResource in the module's build-profile.json5 file, 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 DrawImage {
  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 required by the developer.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  10. build() {
  11. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  12. Canvas(this.context)
  13. .width('100%')
  14. .height('100%')
  15. .backgroundColor('#D5D5D5')
  16. .onReady(() => {
  17. let offContext = this.offCanvas.getContext("2d", this.settings)
  18. offContext.drawImage(this.img, 0, 0, 500, 500, 0, 0, 400, 300)
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

createImageData

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

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

Creates a new ImageData object with the specified width and height based on the current ImageData object. For details, see ImageData. This API involves memory copy and is time-consuming. Avoid frequent use. The example for createImageData is the same as that for putImageData.

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.

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

Default unit: vp

sh number Yes

Height of the ImageData.

The abnormal 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 a new ImageData object based on an existing ImageData object (without copying the image data). See ImageData. This API involves memory copy and is time-consuming. Avoid frequent use. For the createImageData example, see putImageData.

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 to be copied.

The abnormal values undefined and null are processed as an ImageData object with width and height being 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

Creates a PixelMap object from the pixels in the specified area of the current canvas. This API involves memory copy and is time-consuming. Avoid frequent use.

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 upper left corner of the area to output.

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

Default unit: vp

sy number Yes

Y coordinate of the upper left corner of the area to output.

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

Default unit: vp

sw number Yes

Width of the area to output.

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

Default unit: vp

sh number Yes

Height of the area to output.

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

Default unit: vp

Return value

Expand
Type Description
PixelMap New PixelMap object.

Example

NOTE
  • The DevEco Studio previewer does not support displaying content drawn using setPixelMap.

  • The resources in this example are not located in the src > main > resource directory. Starting from DevEco Studio 6.0.0 Beta2, when creating a new project or module, the default module does not package resources outside the resources directory. You need to enable the related switch: set buildOption > resOptions > copyCodeResource > enable to true in the module's build-profile.json5. For details, see 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. // "common/images/example.jpg" needs to be replaced with the image resource file required by the developer.
  8. private img: ImageBitmap = new ImageBitmap("common/images/example.jpg");
  9. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  10. build() {
  11. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  12. Canvas(this.context)
  13. .width('100%')
  14. .height('100%')
  15. .backgroundColor('#ffff00')
  16. .onReady(() => {
  17. let offContext = this.offCanvas.getContext("2d", this.settings)
  18. offContext.drawImage(this.img, 100, 100, 130, 130)
  19. let pixelmap = offContext.getPixelMap(150, 150, 130, 130)
  20. offContext.setPixelMap(pixelmap)
  21. let image = this.offCanvas.transferToImageBitmap()
  22. this.context.transferFromImageBitmap(image)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

setPixelMap

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

setPixelMap(value?: PixelMap): void

Draws the currently passed-in PixelMap object on the canvas. For the setPixelMap example, see 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.

Abnormal values undefined and null are treated as invalid values and will not be drawn.

Default value: null

getImageData

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

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

Creates an ImageData object from the pixels in the specified area of the current canvas. This API involves memory copy and is time-consuming. Avoid frequent use.

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 upper left corner of the output area.

Abnormal values undefined, null, NaN, and Infinity are processed as 0.

Default unit: vp

sy number Yes

Y coordinate of the upper left corner of the output area.

Abnormal values undefined, null, NaN, and Infinity are processed as 0.

Default unit: vp

sw number Yes

Width of the output area.

Abnormal values undefined, null, NaN, and Infinity are processed as 0.

Default unit: vp

sh number Yes

Height of the output area.

Abnormal values undefined, null, NaN, and Infinity are processed 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 > resOptions > copyCodeResource in the module's build-profile.json5 file, 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. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  8. // Replace "/common/images/1234.png" with the image resource file required by the developer.
  9. private img:ImageBitmap = new ImageBitmap("/common/images/1234.png");
  10. build() {
  11. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  12. Canvas(this.context)
  13. .width('100%')
  14. .height('100%')
  15. .backgroundColor('#ffff00')
  16. .onReady(() => {
  17. let offContext = this.offCanvas.getContext("2d", this.settings)
  18. offContext.drawImage(this.img, 0, 0, 130, 130)
  19. let imageData = offContext.getImageData(50,50,130,130)
  20. offContext.putImageData(imageData, 150, 150)
  21. let image = this.offCanvas.transferToImageBitmap()
  22. this.context.transferFromImageBitmap(image)
  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): void

Fills a new rectangular area with ImageData data.

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 that contains pixel values.

Abnormal values undefined or null are treated as invalid values, and no drawing is performed.

dx number | string10+ Yes

Offset of the fill area on the x-axis.

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

Default unit: vp

dy number | string10+ Yes

Offset of the fill area on the y-axis.

Abnormal 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. 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. let imageDataNum = offContext.createImageData(100, 100)
  17. let imageData = offContext.createImageData(imageDataNum)
  18. for (let i = 0; i < imageData.data.length; i += 4) {
  19. imageData.data[i + 0] = 112
  20. imageData.data[i + 1] = 112
  21. imageData.data[i + 2] = 112
  22. imageData.data[i + 3] = 255
  23. }
  24. offContext.putImageData(imageData, 10, 10)
  25. let image = this.offCanvas.transferToImageBitmap()
  26. this.context.transferFromImageBitmap(image)
  27. })
  28. }
  29. .width('100%')
  30. .height('100%')
  31. }
  32. }

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

Uses ImageData data to clip and fill a new rectangular area.

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 containing pixel values.

Invalid values undefined and null are treated as invalid and no drawing is performed.

dx number | string10+ Yes

X-axis offset of the fill area.

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

Default unit: vp

dy number | string10+ Yes

Y-axis offset of the fill area.

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

Default unit: vp

dirtyX number | string10+ Yes

X-axis offset from the upper-left corner of the source image to the upper-left corner of the rectangular clipping region of the source image data.

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

Default unit: vp

dirtyY number | string10+ Yes

Y-axis offset from the upper-left corner of the source image to the upper-left corner of the rectangular clipping region of the source image data.

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

Default unit: vp

dirtyWidth number | string10+ Yes

Width of the rectangular clipping region of the source image data.

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

Default unit: vp

dirtyHeight number | string10+ Yes

Height of the rectangular clipping region of the source image data.

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. 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. let imageDataNum = offContext.createImageData(100, 100)
  17. let imageData = offContext.createImageData(imageDataNum)
  18. for (let i = 0; i < imageData.data.length; i += 4) {
  19. imageData.data[i + 0] = 112
  20. imageData.data[i + 1] = 112
  21. imageData.data[i + 2] = 112
  22. imageData.data[i + 3] = 255
  23. }
  24. offContext.putImageData(imageData, 10, 10, 0, 0, 100, 50)
  25. let image = this.offCanvas.transferToImageBitmap()
  26. this.context.transferFromImageBitmap(image)
  27. })
  28. }
  29. .width('100%')
  30. .height('100%')
  31. }
  32. }

setLineDash

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

setLineDash(segments: number[]): void

Sets the dash line style of 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
segments number[] Yes

Array describing how line segments alternate and the length of the spacing between segments.

Anomalous values undefined or 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. 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('#D5D5D5')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.arc(100, 75, 50, 0, 6.28)
  17. offContext.setLineDash([10, 20])
  18. offContext.stroke()
  19. let image = this.offCanvas.transferToImageBitmap()
  20. this.context.transferFromImageBitmap(image)
  21. })
  22. }
  23. .width('100%')
  24. .height('100%')
  25. }
  26. }

transferFromImageBitmap

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

transferFromImageBitmap(bitmap: ImageBitmap): void

Displays the given 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 be displayed.

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

getLineDash

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

getLineDash(): number[]

Obtains the dash line style of the current 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

Return value

Expand
Type Description
number[]

Array that describes how line segments alternate and the spacing length.

The abnormal values 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 OffscreenCanvasGetLineDash {
  5. @State message: string = 'Hello World';
  6. private settings: RenderingContextSettings = new RenderingContextSettings(true);
  7. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  8. private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600);
  9. build() {
  10. Row() {
  11. Column() {
  12. Text(this.message)
  13. .fontSize(50)
  14. .fontWeight(FontWeight.Bold)
  15. Canvas(this.context)
  16. .width('100%')
  17. .height('100%')
  18. .backgroundColor('#D5D5D5')
  19. .onReady(() => {
  20. let offContext = this.offCanvas.getContext("2d", this.settings)
  21. offContext.arc(100, 75, 50, 0, 6.28)
  22. offContext.setLineDash([10, 20])
  23. offContext.stroke()
  24. let res = offContext.getLineDash()
  25. this.message = JSON.stringify(res)
  26. let image = this.offCanvas.transferToImageBitmap()
  27. this.context.transferFromImageBitmap(image)
  28. })
  29. }
  30. .width('100%')
  31. }
  32. .height('100%')
  33. }
  34. }

restore

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

restore(): void

Restores the saved drawing context.

NOTE

When the number of restore() calls does not exceed the number of save() calls, the stored drawing state is popped from the stack and the attributes, clipping path, and transformation matrix values of the CanvasRenderingContext2D object are restored.

When the number of restore() calls exceeds the number of save() calls, this method does nothing.

When no state is saved, this method 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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.save() // save the default state
  17. offContext.fillStyle = "#00ff00"
  18. offContext.fillRect(20, 20, 100, 100)
  19. offContext.restore() // restore to the default state
  20. offContext.fillRect(150, 75, 100, 100)
  21. let image = this.offCanvas.transferToImageBitmap()
  22. this.context.transferFromImageBitmap(image)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

save

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

save(): void

Saves the current drawing 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

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. 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('#ffff00')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. offContext.save() // save the default state
  17. offContext.fillStyle = "#00ff00"
  18. offContext.fillRect(20, 20, 100, 100)
  19. offContext.restore() // restore to the default state
  20. offContext.fillRect(150, 75, 100, 100)
  21. let image = this.offCanvas.transferToImageBitmap()
  22. this.context.transferFromImageBitmap(image)
  23. })
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. }

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 effect on the offscreen 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. 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. let grad = offContext.createLinearGradient(50,0, 300,100)
  17. grad.addColorStop(0.0, 'rgb(39,135,217)')
  18. grad.addColorStop(0.5, 'rgb(255,238,240)')
  19. grad.addColorStop(1.0, 'rgb(23,169,141)')
  20. offContext.fillStyle = grad
  21. offContext.fillRect(0, 0, 400, 400)
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

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

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

If an invalid value (undefined or null) is passed, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

y0 number Yes

Y-coordinate of the start circle.

If an invalid value (undefined or null) is passed, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

r0 number Yes

Radius of the start circle. Must be non-negative and finite.

If an invalid value (undefined or null) is passed, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

x1 number Yes

X-coordinate of the end circle.

If an invalid value (undefined or null) is passed, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

y1 number Yes

Y-coordinate of the end circle.

If an invalid value (undefined or null) is passed, this API returns undefined. NaN and Infinity are treated as invalid values.

Default unit: vp

r1 number Yes

Radius of the end circle. Must be non-negative and finite.

If an invalid value (undefined or null) is passed, 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 effect on the offscreen 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. 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. let grad = offContext.createRadialGradient(200,200,50, 200,200,200)
  17. grad.addColorStop(0.0, 'rgb(39,135,217)')
  18. grad.addColorStop(0.5, 'rgb(255,238,240)')
  19. grad.addColorStop(1.0, 'rgb(112,112,112)')
  20. offContext.fillStyle = grad
  21. offContext.fillRect(0, 0, 440, 440)
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

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.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Expand
Name Type Mandatory Description
startAngle number Yes

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

Abnormal values undefined and null are processed as 0, and NaN and Infinity are processed as invalid values.

Unit: radian

x number Yes

X-coordinate of the center of the conic gradient.

Abnormal values undefined and null are processed as 0, and NaN and Infinity are processed as invalid values.

Default unit: vp

y number Yes

Y-coordinate of the center of the conic gradient.

Abnormal values undefined and null are processed as 0, and NaN and Infinity are processed as invalid values.

Default unit: vp

Return value

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

Example

Collapse
Word wrap
Dark theme
Copy code
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct OffscreenCanvasConicGradientPage {
  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('#ffffff')
  14. .onReady(() => {
  15. let offContext = this.offCanvas.getContext("2d", this.settings)
  16. let grad = offContext.createConicGradient(0, 50, 80)
  17. grad.addColorStop(0.0, '#ff0000')
  18. grad.addColorStop(0.5, '#ffffff')
  19. grad.addColorStop(1.0, '#00ff00')
  20. offContext.fillStyle = grad
  21. offContext.fillRect(0, 30, 100, 100)
  22. let image = this.offCanvas.transferToImageBitmap()
  23. this.context.transferFromImageBitmap(image)
  24. })
  25. }
  26. .width('100%')
  27. .height('100%')
  28. }
  29. }

CanvasFillRule

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

type CanvasFillRule = "evenodd" | "nonzero"

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

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"

Even-odd rule.

This rule determines whether a point on the canvas is inside a shape by casting a ray from the point 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, it is outside.

"nonzero"

Nonzero rule.

This rule determines whether a point on the canvas is inside a shape by casting a ray from the point in any direction and checking the intersections between the ray and the shape path. The initial count is 0. Each segment of the path is assigned a direction value. The count increases by 1 when the path crosses the ray from left to right, and decreases by 1 when it crosses from right to left. If the final result is 0, the point is outside the shape; otherwise, it is inside.

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. // Nonzero winding 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 nonzero winding rule.
  23. offContext.fillText('nonzero', 65, 200)
  24. // Even-odd winding 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 winding 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. }

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 Read-only property. Width of the text block.
height number Yes No Read-only property. Height of the text block.
actualBoundingBoxAscent number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the top of the bounding rectangle of the drawn text.
actualBoundingBoxDescent number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the bottom of the bounding rectangle of the drawn text.
actualBoundingBoxLeft number Yes No Read-only property. Distance from the alignment point determined by the textAlign attribute to the left side of the text bounding rectangle, parallel to the baseline.
actualBoundingBoxRight number Yes No Read-only property. Distance from the alignment point determined by the textAlign attribute to the right side of the text bounding rectangle, parallel to the baseline.
alphabeticBaseline number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the alphabetic baseline of the line box.
emHeightAscent number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the top of the em square in the line box.
emHeightDescent number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the bottom of the em square in the line box.
fontBoundingBoxAscent number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the top of the highest bounding rectangle of all fonts used to draw the text.
fontBoundingBoxDescent number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the bottom of the bounding rectangle of all fonts used to draw the text.
hangingBaseline number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the hanging baseline of the line box.
ideographicBaseline number Yes No Read-only property. Distance from the horizontal line indicated by the textBaseline attribute to the ideographic baseline of the line box.
Search in References
Enter a keyword.