所述插件核心API提供了一系列可用于执行自定义代码钩。您可以使用afterLayout挂钩来考虑指定的阈值来创建线性渐变。然后,您必须将其分配给的borderColor
属性dataset
。
请看下面的可运行代码,看看它能正常工作。
const threshold = 25;
new Chart('myChart', {
type: 'line',
plugins: [{
afterLayout: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let yAxis = chart.scales["y-axis-0"];
let yThreshold = yAxis.getPixelForValue(threshold);
let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);
gradient.addColorStop(0, 'green');
let offset = 1 / yAxis.bottom * yThreshold;
gradient.addColorStop(offset, 'green');
gradient.addColorStop(offset, 'red');
gradient.addColorStop(1, 'red');
chart.data.datasets[0].borderColor = gradient;
ctx.restore();
}
}],
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
datasets: [{
label: 'My Dataset',
data: [32, 44, 29, 33, 18, 15, 30],
fill: false
}]
},
options: {
legend: {
display: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句