问题
How i can add background color between two lines in Y-Axis in chartjs if you checked the figure i need to be able to do something like this set a color between two lines first one is orange and then blue or whatever, i checked the official docs but i didn't find anything.
also here is my chartjs configurations
this.options = {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [
{
gridLines: {
display: true,
color: chartjs.axisLineColor,
},
ticks: {
fontColor: chartjs.textColor,
},
},
],
yAxes: [
{
gridLines: {
display: true,
color: chartjs.axisLineColor,
},
ticks: {
fontColor: chartjs.textColor,
},
},
],
},
legend: {
labels: {
fontColor: chartjs.textColor,
},
},
};
回答1:
You have to register your own plugin to fill chartArea before chart line drawing:
Chart.pluginService.register({
beforeDraw: function (chart, easing) {
if (chart.config.options.fillColor) {
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
ctx.save();
ctx.fillStyle = chart.config.options.fillColor;
ctx.fillRect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
ctx.restore();
}
}
});
var chartData = {
labels: ['a', 'b', 'c', 'd'],
datasets: [{
label: 'value',
backgroundColor: 'rgba(255, 0, 255, 0.8)',
borderColor: 'blue',
data: [30, 50, 25, 10]
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{ ticks: { max: 60 } }]
},
legend: { display: false },
fillColor: 'rgba(255, 128, 0, 0.8)',
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" height="300" width="500"></canvas>
来源:https://stackoverflow.com/questions/49301665/how-to-add-background-color-between-two-lines-in-yaxis-chartjs