[Chartjs]-How to add background color between two lines in yAxis Chartjs

4👍

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>

Leave a comment