Chart.js Line chart with different background colors for each section - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Chart.js Line chart with different background colors for each section

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/* ww w .  ja va 2 s .c o m*/
Chart.pluginService.register({
  beforeDraw: function (chart, easing) {
  if (chart.config.options.chartArea && chart.config.options.chartArea.backgroundColor) {
    var ctx = chart.chart.ctx;
    var chartArea = chart.chartArea;
    var meta = chart.getDatasetMeta(0);
    var start = meta.data[1]._model.x;
    var stop  = meta.data[2]._model.x;
    console.log (start,stop);
    ctx.save();
    ctx.fillStyle = chart.config.options.chartArea.backgroundColor;
    console.log (chartArea);
    ctx.fillRect(start, chartArea.top, stop - start, chartArea.bottom - chartArea.top);
    ctx.restore();
    }
  }
});
var ctx = document.getElementById("myLine").getContext('2d');
input = {
  type: 'line',
  data: {
    labels:  ['Jan','Feb','Mar','Apr','May'],
    datasets: [{
      data: [9,6,9,3,5,7],
      label: "Dataset 1",
      borderColor: "#3e95cd",
      fill: false
      }]
    },
    options: {
      responsive:true,
      animation : false,
      bezierCurve : true,
      chartArea: {
        backgroundColor: 'rgba(251, 85, 85, 0.4)'
      },
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero:false
            }
          }]
        },
    }
}
var myLine = new Chart(ctx, input);
    });

      </script> 
   </head> 
   <body> 
      <canvas id="myLine" width="1200" height="400"></canvas>  
   </body>
</html>

Related Tutorials