二维码

渐变

  绘制几何图形时,通过给几何对象的style属性设置colorfillColor 属性可指定几何图形边框效果和填充效果,而且这两个属性除了可以 使用颜色 外,还可以指定为 渐变对象图案/纹理对象

  渐变风格包括 “线性渐变”和“径向渐变”两种类型。AnyGraph 设计了渐变对象类 Gradient,可实现这两种类型的渐变效果。

线性渐变

  线性渐变是一种颜色过渡方式,它以一条直线(水平或垂直)为轴线,从起点到终点颜色进行顺序渐变。

  下面这个示例展示了线性渐变效果:

源代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<script type="module">
// graph对象
let graph = new Graph({
"target": "graphWrapper"
});

// 网格水印层
BgUtil.generateGrid(Object.assign({ "interval": 10, "graph": graph }, graph.getSize()));

// 新建绘图图层
let layer = graph.addLayer();
let [x, y, width, height] = [100, 80, 600, 100];

// 按60deg生成色带(6份)
let colorBand = ["#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FF0000"];
let gradient = new Gradient({
"type": "linear",
"coords": { "x1": x, "y1": y, "x2": x + width, "y2": y },
"colorStops": [
{ "offset": "0", "color": colorBand[0] },
{ "offset": "0.166", "color": colorBand[1] },
{ "offset": "0.333", "color": colorBand[2] },
{ "offset": "0.5", "color": colorBand[3] },
{ "offset": "0.667", "color": colorBand[4] },
{ "offset": "0.833", "color": colorBand[5] },
{ "offset": "1", "color": colorBand[0] },
]
});

layer.getSource().add(new Rect({
x, y, width, height, "style": { "fillColor": gradient, "fillStyle": 1, "color": "none" }
}));

for (let i = 0; i < 7; i++) {
layer.getSource().add(new Text({
"x": x + width / 6 * i,
"y": y + height + 40,
"text": 60 * i, "style": { "fillStyle": 1, "fillColor": "#000000", "fontSize": 36, "fontName": "黑体", "textAlign": "center", "textBaseline": "middle" }
}));
}
</script>

径向渐变

  径向渐变是指从起点到终点颜色从内到外进行圆形渐变(从中间向外拉)。

  下面这个示例展示径向渐变效果:

源代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<script type="module">
import {
Graph, BgUtil, Color, MathUtil, GGeometryType, Rect, Circle, Gradient, Text
} from "../../src/index.js";

// graph对象
let graph = new Graph({
"target": "graphWrapper"
});

// 网格水印层
BgUtil.generateGrid(Object.assign({ "interval": 10, "graph": graph }, graph.getSize()));

// 新建绘图图层
let layer = graph.addLayer();
let colorSet = ["red", "orange", "gold", "green", "black", "blue"];
let radius = 60;
for (let x = 100; x < 800; x += radius * 2.5) {
for (let y = 100; y < 500; y += radius * 2.5) {
let color = colorSet[MathUtil.getRandomNum(0, colorSet.length - 1)];
let colorBand = Color.band(color, 10);

// 渐变对象
let gradient = new Gradient({
"type": "radial",
"coords": { "x1": x + radius / 2, "y1": y + radius / 2, "r1": 0, "x2": x, "y2": y, "r2": radius },
"colorStops": [{
"offset": "0.1",
"color": colorBand[2],
}, {
"offset": "0.95",
"color": colorBand[7]
}]
});
// 圆
layer.getSource().add(new Circle({
x, y, radius,
"style": { "fillColor": gradient, "fillStyle": 1, "color": "none" }
}));
}
}