ts-components-canvas-canvasgradient.md 1.8 KB
Newer Older
Z
zengyawen 已提交
1
# CanvasGradient
Z
zengyawen 已提交
2

E
ester.zhou 已提交
3
**CanvasGradient** provides a canvas gradient object.
Z
zengyawen 已提交
4

E
ester.zhou 已提交
5
>  **NOTE**
E
esterzhou 已提交
6
> 
E
ester.zhou 已提交
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.
Z
zengyawen 已提交
8 9


E
esterzhou 已提交
10

Z
zengyawen 已提交
11
## addColorStop
Z
zengyawen 已提交
12

Z
zengyawen 已提交
13
addColorStop(offset: number, color: string): void
Z
zengyawen 已提交
14

Z
zengyawen 已提交
15
Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color.
Z
zengyawen 已提交
16

E
ester.zhou 已提交
17 18
Since API version 9, this API is supported in ArkTS widgets.

E
esterzhou 已提交
19 20 21

**Parameters**

E
ester.zhou 已提交
22 23 24 25
| Name    | Type    | Mandatory  | Default Value      | Description                          |
| ------ | ------ | ---- | --------- | ---------------------------- |
| offset | number | Yes   | 0         | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.|
| color  | string | Yes   | '#ffffff' | Gradient color to set.                    |
E
ester.zhou 已提交
26

E
esterzhou 已提交
27 28

**Example**
E
ester.zhou 已提交
29 30

  ```ts
E
ester.zhou 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
// xxx.ets
@Entry
@Component
struct Page45 {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() => {
          var grad = this.context.createLinearGradient(50, 0, 300, 100)
E
ester.zhou 已提交
46 47 48
          grad.addColorStop(0.0, '#ff0000')
          grad.addColorStop(0.5, '#ffffff')
          grad.addColorStop(1.0, '#00ff00')
E
ester.zhou 已提交
49 50 51 52 53 54 55 56
          this.context.fillStyle = grad
          this.context.fillRect(0, 0, 500, 500)
        })
    }
    .width('100%')
    .height('100%')
  }
}
E
ester.zhou 已提交
57 58 59 60
  ```
  ![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png)