ChartJs - set background color between ticks in line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

ChartJs - set background color between ticks in line chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>chart.js 2.1</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from  www  .  java  2s . co m
      Chart.pluginService.register({
        beforeDraw: function(chart, easing) {
          if (chart.config.options.chartArea && chart.config.options.chartArea.backgroundColor) {
            var helpers = Chart.helpers;
            var ctx = chart.chart.ctx;
            var chartArea = chart.chartArea;
            var values = chart.data.datasets[0].data; 
            var rowCount = Math.ceil(Math.max.apply(null, values) / 10);
            var width = chartArea.right - chartArea.left;
            var height = chartArea.bottom - chartArea.top
            var rowHeight = height / rowCount;
            ctx.save();
            ctx.fillStyle = chart.config.options.chartArea.backgroundColor;
            var startPoint = chartArea.top
            while (startPoint < chartArea.bottom) {
              ctx.fillRect(chartArea.left, startPoint, width, rowHeight);
              startPoint += rowHeight * 2;
            }
            ctx.restore();
          }
        }
      });
      var config = {
        type: 'line',
        data: {
          labels: ["January", "February", "March", "April", "May", "June", "July"],
          datasets: [{
            label: "My First dataset",
            data: [65, 0, 80, 81, 56, 85, 40],
            fill: false
          }]
        },
        options: {
          chartArea: {
            backgroundColor: 'rgba(251, 85, 85, 0.4)'
          }
        }
      };
      var ctx = document.getElementById("myChart").getContext("2d");
      new Chart(ctx, config);
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart"></canvas>  
   </body>
</html>

Related Tutorials