【问题标题】:How to set specific height for chartJs background color in terms of yAxis value如何根据yAxis值设置chartJs背景颜色的特定高度
【发布时间】:2020-09-16 20:49:05
【问题描述】:
我有一个使用chartJs see app.component.ts on Stackblitz 的折线图
如您所见,backgroundColor: 'rgba(250,174,50,1)' 只为整个图表提供颜色。我需要的是背景颜色,直到特定的yAxis 值。在此示例中,例如直到 200,我想看到橙色,其余为白色,如下所示.
有什么办法吗?
【问题讨论】:
标签:
javascript
angular
typescript
chart.js
html2canvas
【解决方案1】:
Plugin Core API 提供了一系列可用于执行自定义代码的挂钩。您可以使用afterLayout 挂钩通过CanvasRenderingContext2D.createLinearGradient() 创建线性渐变并将其分配给数据集的backgroundColor 属性。
plugins: [{
afterLayout: c => {
let dataset = c.data.datasets[0];
let thresholdValueIndex = dataset.data.indexOf(dataset.fillThreshold);
let xAxis = c.scales["x-axis-0"];
let xRight = xAxis.getPixelForTick(thresholdValueIndex);
let gradientFill = c.ctx.createLinearGradient(xAxis.left, 0, xRight, 0);
gradientFill.addColorStop(0, "rgb(250,174,50");
gradientFill.addColorStop(1, "rgb(250,174,50");
gradientFill.addColorStop(1, "white");
dataset.backgroundColor = gradientFill;
}
}],
此代码需要在数据集上定义属性 fillThreshold,其值必须对应于也包含在 data 数组中的值。
请查看您修改后的StackBlitz。