在 Chart.js 里实现渐变背景色

为折线图里的一条线设置渐变的背景色


利用 chart.js 生成一个 chart 实例

1
2
3
4
5
6
7
8
9
// 得到一个 canvas 上下文
var ctx = document.getElementById('canvas').getContext('2d');

// 创建 chart
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});

上面代码里传入的 data 选项就是用来画线的数据,其中包含 标签(labels)数据集(datasets)

如果只有一条线,只需要在 datasets 里放一组数据

1
2
3
4
5
6
7
8
9
10
data: {
labels: labels,
datasets: [{
data: data,
borderWidth: 2.5,
borderColor: "#328fde",
pointRadius: 0,
backgroundColor: "#fff"
}]
},

我们为这条线设置了 宽度颜色节点的半径背景色

重点看一下背景色

chart.jsbackgroundColor 值的要求是:

When supplying colors to Chart options, you can use a number of formats. You can specify the color as a string in hexadecimal, RGB, or HSL notations. If a color is needed, but not specified, Chart.js will use the global default color. This color is stored at Chart.defaults.global.defaultColor. It is initially set to ‘rgba(0, 0, 0, 0.1)’.

你可以设置多种格式的颜色作为背景,如果没有指定,它的默认值 是 rgba(0, 0, 0, 0.1)

You can also pass a CanvasGradient object. You will need to create this before passing to the chart, but using it you can achieve some interesting effects.

我们还可以传入一个 CanvasGradient

CanvasGradient 接口表示描述渐变的不透明对象。通过 CanvasRenderingContext2D.createLinearGradient() 或 CanvasRenderingContext2D.createRadialGradient() 的返回值得到.

CanvasGradient.addColorStop() 添加一个由偏移(offset)和颜色(color)定义的断点到渐变中。

我们就利用 CanvasGradient 为线条添加渐变的背景色

1
2
3
4
5
6
7

// 通过 createLinearGradient 创建 CanvasGradient 对象
var gradientStroke = ctx.createLinearGradient(0, 0, 0, 100);

// 定义渐变的 偏移 和 颜色
gradientStroke.addColorStop(0, "#328fdebf");
gradientStroke.addColorStop(1, "#ffffff9e");

然后,我们把 chart 数据集里的背景色 更改为 这个 CanvasGradient 对象

1
2
3
4
5
6
7
8
9
10
data: {
labels: options.labels,
datasets: [{
data: options.data,
borderWidth: 2.5,
borderColor: "#328fde",
pointRadius: 0,
backgroundColor: gradientStroke // 更新背景色为 gradientStroke
}]
}

这样,就实现了一个渐变的背景

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2020/03/06/gradient-background-color-in-chart-js/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

开发小程序遇到的一些问题