Draw a vertical line on hover in chartjs - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Draw a vertical line on hover in chartjs

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.0.0/Chart.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from w ww .  ja  v a  2 s  .co  m*/
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
responsive: false,
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3]
    }]
  }
});
// Hook into main event handler
var parentEventHandler = Chart.Controller.prototype.eventHandler;
Chart.Controller.prototype.eventHandler = function() {
  var ret = parentEventHandler.apply(this, arguments);
  this.clear();
  this.draw();
   // Draw the vertical line here
  var eventPosition = Chart.helpers.getRelativePosition(arguments[0], this.chart);
  this.chart.ctx.beginPath();
  this.chart.ctx.moveTo(eventPosition.x, 30);
  this.chart.ctx.strokeStyle = "#ff0000";
  this.chart.ctx.lineTo(eventPosition.x, 340);
  this.chart.ctx.stroke();
  return ret;
};
    }

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

Related Tutorials