• 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
17Since API version 9, this API is supported in ArkTS widgets.
18
19
20**Parameters**
21
22| Name    | Type    | Mandatory  | Default Value      | Description                          |
23| ------ | ------ | ---- | --------- | ---------------------------- |
24| offset | number | Yes   | 0         | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.|
25| color  | string | Yes   | '#ffffff' | Gradient color to set. For details about the color notation, see the description of the string type in [ResourceColor](ts-types.md#resourcecolor).                    |
26
27
28**Example**
29
30  ```ts
31// xxx.ets
32@Entry
33@Component
34struct Page45 {
35  private settings: RenderingContextSettings = new RenderingContextSettings(true)
36  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
37
38  build() {
39    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
40      Canvas(this.context)
41        .width('100%')
42        .height('100%')
43        .backgroundColor('#ffff00')
44        .onReady(() => {
45          var grad = this.context.createLinearGradient(50, 0, 300, 100)
46          grad.addColorStop(0.0, '#ff0000')
47          grad.addColorStop(0.5, '#ffffff')
48          grad.addColorStop(1.0, '#00ff00')
49          this.context.fillStyle = grad
50          this.context.fillRect(0, 0, 400, 400)
51        })
52    }
53    .width('100%')
54    .height('100%')
55  }
56}
57  ```
58  ![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png)
59
60
61