• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# CanvasPattern
2
3**CanvasPattern** represents an object, created by the [createPattern](ts-canvasrenderingcontext2d.md#createpattern) API, describing an image filling pattern based on the image and repetition mode.
4
5>  **NOTE**
6>
7>  The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8
9## Methods
10
11### setTransform
12
13setTransform(transform?: Matrix2D): void
14
15Uses a **Matrix2D** object as a parameter to perform matrix transformation on the current **CanvasPattern** object.
16
17**Widget capability**: This API can be used in ArkTS widgets since API version 9.
18
19**Atomic service API**: This API can be used in atomic services since API version 11.
20
21**System capability**: SystemCapability.ArkUI.ArkUI.Full
22
23**Parameters**
24
25| Name     | Type | Mandatory| Description  |
26| --------- | -------------- | ------ | ---------- |
27| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No | Transformation matrix.<br>Default value: **null**|
28
29## Example
30
31This example demonstrates how to apply matrix transformations to a **CanvasPattern** object using the **setTransform** API.
32
33```ts
34// xxx.ets
35@Entry
36@Component
37struct CanvasPatternPage {
38  private settings: RenderingContextSettings = new RenderingContextSettings(true)
39  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
40  private matrix: Matrix2D = new Matrix2D()
41  private img: ImageBitmap = new ImageBitmap("common/pattern.jpg")
42  private pattern: CanvasPattern | null = null
43
44  build() {
45      Column() {
46        Button("Click to set transform")
47          .onClick(() => {
48            this.matrix.scaleY = 1
49            this.matrix.scaleX = 1
50            this.matrix.translateX = 50
51            this.matrix.translateY = 200
52            if (this.pattern) {
53              this.pattern.setTransform(this.matrix)
54            }
55            this.context.fillRect(0, 0, 480, 720)
56          })
57          .width("45%")
58          .margin("5px")
59        Canvas(this.context)
60          .width('100%')
61          .height('80%')
62          .backgroundColor('#FFFFFF')
63          .onReady(() => {
64            this.pattern = this.context.createPattern(this.img, 'no-repeat')
65            this.matrix.scaleY = 0.5
66            this.matrix.scaleX = 0.5
67            this.matrix.translateX = 50
68            this.matrix.translateY = 50
69            if (this.pattern) {
70              this.context.fillStyle = this.pattern
71              this.pattern.setTransform(this.matrix)
72            }
73            this.context.fillRect(0, 0, 480, 720)
74          })
75      }
76      .width('100%')
77      .height('100%')
78  }
79}
80```
81
82![CanvasPattern](./figures/canvas_pattern.gif)
83