扫码一下
查看教程更方便
为图表选项提供颜色时,我们可以使用多种格式。 我们可以将颜色指定为十六进制、rgb 或 hsl 表示法的字符串。 如果需要颜色但未指定,chart.js 将使用全局默认颜色。 有 3 个颜色选项,存储在 chart.defaults 中,可以设置:
名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
backgroundcolor | color | rgba(0, 0, 0, 0.1) | 背景色 |
bordercolor | color | rgba(0, 0, 0, 0.1) | 边框颜色 |
color | color | #666 | 字体颜色 |
我们还可以传递一个 canvasgradient
对象。 需要在传递给图表之前创建它,但使用它可以实现一些有趣的效果。
另一种选择是传递 canvaspattern
或 canvasgradient
对象而不是字符串颜色。
例如,如果想用图像中的模式填充数据集,我们可以执行以下操作。
const img = new image();
img.src = 'https://example.com/my_image.png';
img.onload = function() {
const ctx = document.getelementbyid('canvas').getcontext('2d');
const fillpattern = ctx.createpattern(img, 'repeat');
const chart = new chart(ctx, {
data: {
labels: ['item 1', 'item 2', 'item 3'],
datasets: [{
data: [10, 20, 30],
backgroundcolor: fillpattern
}]
}
});
};
为数据图形使用图案填充可以帮助有视力缺陷(例如色盲或部分视力)的查看者更轻松地理解我们的数据。
使用 patternomaly
库,我们可以生成填充数据集的模式。
const chartdata = {
datasets: [{
data: [45, 25, 20, 10],
backgroundcolor: [
pattern.draw('square', '#ff6384'),
pattern.draw('circle', '#36a2eb'),
pattern.draw('diamond', '#cc65fe'),
pattern.draw('triangle', '#ffce56')
]
}],
labels: ['red', 'blue', 'purple', 'yellow']
};