• 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
17Since API version 9, this API is supported in ArkTS widgets.
18
19**Parameters**
20
21| Name     | Type                                                 | Mandatory| Default Value| Description      |
22| --------- | ----------------------------------------------------- | ---- | ------ | ---------- |
23| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No  | null   | Transformation matrix.|
24
25**Example**
26
27```ts
28// xxx.ets
29@Entry
30@Component
31struct CanvasPatternPage {
32  private settings: RenderingContextSettings = new RenderingContextSettings(true)
33  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
34  private matrix: Matrix2D = new Matrix2D()
35  private img: ImageBitmap = new ImageBitmap("common/pattern.jpg")
36  private pattern : CanvasPattern | null = null
37
38  build() {
39      Column() {
40        Button("Click to set transform")
41          .onClick(() => {
42            this.matrix.scaleY = 1
43            this.matrix.scaleX = 1
44            this.matrix.translateX = 50
45            this.matrix.translateY = 200
46            if (this.pattern) {
47              this.pattern.setTransform(this.matrix)
48            }
49            this.context.fillRect(0, 0, 480, 720)
50          })
51          .width("45%")
52          .margin("5px")
53        Canvas(this.context)
54          .width('100%')
55          .height('80%')
56          .backgroundColor('#FFFFFF')
57          .onReady(() => {
58            this.pattern = this.context.createPattern(this.img, 'no-repeat')
59            this.matrix.scaleY = 0.5
60            this.matrix.scaleX = 0.5
61            this.matrix.translateX = 50
62            this.matrix.translateY = 50
63            if (this.pattern) {
64              this.context.fillStyle = this.pattern
65              this.pattern.setTransform(this.matrix)
66            }
67            this.context.fillRect(0, 0, 480, 720)
68          })
69      }
70      .width('100%')
71      .height('100%')
72  }
73}
74```
75
76![CanvasPattern](./figures/canvas_pattern.gif)
77