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

L
lanyill 已提交
3 4
渐变对象。

H
geshi  
HelloCrease 已提交
5
>  **说明:**
L
lanyill 已提交
6
> 
H
HelloCrease 已提交
7
>  从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
Z
zengyawen 已提交
8 9 10



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

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

Z
zengyawen 已提交
15
设置渐变断点值,包括偏移和颜色。
Z
zengyawen 已提交
16

L
lanyill 已提交
17 18 19

**参数:**

Y
yamila 已提交
20 21 22 23
| 参数     | 类型     | 必填   | 默认值       | 描述                           |
| ------ | ------ | ---- | --------- | ---------------------------- |
| offset | number | 是    | 0         | 设置渐变点距离起点的位置占总体长度的比例,范围为0到1。 |
| color  | string | 是    | '#ffffff' | 设置渐变的颜色。                     |
Z
zengyawen 已提交
24

L
lanyill 已提交
25 26

**示例:**
H
HelloCrease 已提交
27

H
geshi  
HelloCrease 已提交
28
  ```ts
Y
yamila 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
// 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)
44 45 46
          grad.addColorStop(0.0, '#ff0000')
          grad.addColorStop(0.5, '#ffffff')
          grad.addColorStop(1.0, '#00ff00')
Y
yamila 已提交
47 48 49 50 51 52 53 54
          this.context.fillStyle = grad
          this.context.fillRect(0, 0, 500, 500)
        })
    }
    .width('100%')
    .height('100%')
  }
}
55 56
  ```
  ![zh-cn_image_0000001194032516](figures/zh-cn_image_0000001194032516.png)
57 58