Acceptable Range Highlighting of Background for line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Acceptable Range Highlighting of Background for line chart

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://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*  w  ww.j  av a2  s  .co m*/
var ctx = document.getElementById("myChart");
var lineSuperDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw : function() {
    var chart = this.chart;
    var ctx = chart.chart.ctx;
    var yRangeBegin = chart.config.data.yRangeBegin;
    var yRangeEnd = chart.config.data.yRangeEnd;
    var xaxis = chart.scales['x-axis-0'];
    var yaxis = chart.scales['y-axis-0'];
    var yRangeBeginPixel = yaxis.getPixelForValue(yRangeBegin);
    var yRangeEndPixel = yaxis.getPixelForValue(yRangeEnd);
    ctx.save();
    for (var yPixel = Math.min(yRangeBeginPixel, yRangeEndPixel); yPixel <= Math.max(yRangeBeginPixel, yRangeEndPixel); ++yPixel) {
      ctx.beginPath();
      ctx.moveTo(xaxis.left, yPixel);
      ctx.strokeStyle = '#00ff00';
      ctx.lineTo(xaxis.right, yPixel);
      ctx.stroke();
    }
    ctx.restore();
    lineSuperDraw.apply(this, arguments);
  }
});
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
    }],
    yRangeBegin : 6.5,
    yRangeEnd : 12.5
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});
    }

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

Related Tutorials