Chart.js to draw horizontal line based on a certain y-value - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Chart.js to draw horizontal line based on a certain y-value

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://rawgit.com/nnnick/Chart.js/v1.0.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  w  w w  .  ja  v a 2 s .  c o m*/
    var data = {
        labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
        datasets: [{
            data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
        }]
    };
    var ctx = document.getElementById("myChart").getContext("2d");
    Chart.types.Line.extend({
        name: "LineWithYLine",
        draw: function () {
            Chart.types.Line.prototype.draw.apply(this, arguments);
            var scale = this.scale
            var ctx = this.chart.ctx;
            var y = scale.calculateY(this.options.lineAtValue);
            ctx.save();
            ctx.strokeStyle = '#ff0000';
            ctx.beginPath();
            ctx.moveTo(Math.round(scale.xScalePaddingLeft), y);
            ctx.lineTo(this.chart.width, y);
            ctx.stroke();
            ctx.restore();
        }
    });
    new Chart(ctx).LineWithYLine(data, {
        datasetFill: false,
        lineAtValue: 7.5
    });
    }

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

Related Tutorials