2👍
✅
Using the afterLayout
hook from the Plugin Core API, this could be written as follows:
plugins: [{
afterLayout: c => {
let dataset = c.data.datasets[0];
let yScale = c.scales['y-axis-0'];
let yBottom = yScale.getPixelForValue(0);
let yGradientStart = yScale.getPixelForValue(dataset.data.find(v => v > 0));
let yTop = yScale.getPixelForValue(Math.max(...dataset.data));
let gradientFill = c.ctx.createLinearGradient(0, yBottom, 0, yTop);
gradientFill.addColorStop(0, "#fff");
let offset = (yBottom - yGradientStart) / (yBottom - yTop);
gradientFill.addColorStop(offset, "#fff");
gradientFill.addColorStop(1, "#7E0100");
dataset.backgroundColor = gradientFill;
}
}],
Please take a look at below runnable code and see how it works.
new Chart("chart", {
type: 'line',
plugins: [{
afterLayout: c => {
let dataset = c.data.datasets[0];
let yScale = c.scales['y-axis-0'];
let yBottom = yScale.getPixelForValue(0);
let yGradientStart = yScale.getPixelForValue(dataset.data.find(v => v > 0));
let yTop = yScale.getPixelForValue(Math.max(...dataset.data));
let gradientFill = c.ctx.createLinearGradient(0, yBottom, 0, yTop);
gradientFill.addColorStop(0, "#fff");
let offset = (yBottom - yGradientStart) / (yBottom - yTop);
gradientFill.addColorStop(offset, "#fff");
gradientFill.addColorStop(1, "#7E0100");
dataset.backgroundColor = gradientFill;
}
}],
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
borderColor: '#7E0100',
data: [0, 120, 200, 350, 200, 120, 0]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
max: 500,
stepSize: 100
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="160"></canvas>
Source:stackexchange.com