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

Javascript examples for Chart.js:Line Chart

Description

Create 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://rawgit.com/nnnick/Chart.js/v1.0.2/Chart.min.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/*w  w  w  .  j a va 2  s  . c  o m*/
Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        Chart.types.Line.prototype.initialize.apply(this, arguments);
        // keep a reference to the original clear
        this.originalClear = this.clear;
        this.clear = function () {
            this.originalClear();
            var unitX = this.datasets[0].points[1].x - this.datasets[0].points[0].x;
            var yTop = this.scale.startPoint;
            var yHeight = this.scale.endPoint - this.scale.startPoint;
            this.chart.ctx.fillStyle = 'rgba(100,100,100,0.8)';
            this.chart.ctx.fillRect(this.datasets[0].points[5].x - 0.5 * unitX, yTop, unitX * 5, yHeight);
            this.chart.ctx.fillRect(this.datasets[0].points[15].x - 0.5 * unitX, yTop, unitX * 5, yHeight);
        }
    }
});
var data = {
    labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Mon", "Tue", "Wed", "Thu", "Fri", "Mon", "Tue", "Wed", "Thu", "Fri", "Mon", "Tue", "Wed", "Thu", "Fri"],
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 59, 80, 81, 56, 65, 59, 80, 81, 56, 65, 59, 80, 81, 56, 65, 59, 80, 81, 56]
    }, {
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: [28, 48, 40, 19, 86, 28, 48, 40, 19, 86, 28, 48, 40, 19, 86, 28, 48, 40, 19, 86]
    }]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).LineAlt(data);
    });

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

Related Tutorials