• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# CanvasGradient
2
3**CanvasGradient** provides a canvas gradient object.
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
10
11## addColorStop
12
13addColorStop(offset: number, color: string): void
14
15Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color.
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| offset | number | Yes | Relative position of the gradient stop along the gradient vector, represented by the ratio of the distance between the gradient stop and the start point to the total length. The value ranges from 0 to 1.<br>If the value of **offset** is less than 0 or greater than 1, there is no gradient effect.            |
28| color  | string | Yes | Gradient color to set. For details about the color notation, see the description of the string type in [ResourceColor](ts-types.md#resourcecolor).<br>Invalid values result in no gradient effect being displayed.|
29
30
31## Example
32
33This example shows how to add a color stop using **addColorStop**.
34
35  ```ts
36  // xxx.ets
37  @Entry
38  @Component
39  struct AddColorStop {
40    private settings: RenderingContextSettings = new RenderingContextSettings(true)
41    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
42
43    build() {
44      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
45        Canvas(this.context)
46          .width('100%')
47          .height('100%')
48          .backgroundColor('#ffff00')
49          .onReady(() => {
50            let grad = this.context.createLinearGradient(50, 0, 300, 100)
51            grad.addColorStop(0.0, '#ff0000')
52            grad.addColorStop(0.5, '#ffffff')
53            grad.addColorStop(1.0, '#00ff00')
54            this.context.fillStyle = grad
55            this.context.fillRect(0, 0, 400, 400)
56          })
57      }
58      .width('100%')
59      .height('100%')
60    }
61  }
62  ```
63  ![en-us_image_0000001194032516](figures/en-us_image_0000001194032516.jpeg)
64
65
66