Chart.js add tooltip at intersection of axes for line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Chart.js add tooltip at intersection of axes for line chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>ChartJS - Line Chart - Y axis scale problem ?</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="http://www.chartjs.org/assets/Chart.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  w w w . j  a  v  a2  s. c  o m*/
var ctx = document.getElementById("chart");
var options = {
    type: 'line',
    data: {
        labels: [1, 2, 4, 6,7, 10] ,
        datasets: [
            {
                backgroundColor: "rgba(151,187,205,0.2)",
                borderColor: "rgba(151,187,205,1)",
                data: [80, 80, 80, 80, 80, 80]
            },
            {
                backgroundColor: "rgba(220,220,220,0.2)",
                borderColor: "rgba(220,220,220,1)",
                data: [8.84, 17.68, 35.36, 53.04, 70.72, 88.4]
            }
        ]
    },
    options: {
        tooltips: {
            enabled: false
        },
        legend: {
            position: 'top'
        }
    }
};
Chart.plugins.register({
    afterInit: function(chart) {
    var intersect = getIntersection();
    console.log(intersect)
     var datasets = chart.data.datasets;
     var labels = chart.data.labels;
     labels.push(intersect.x)
      labels.sort(function(a,b){return a - b});
    y = labels.indexOf(intersect.x);
    chart.data.datasets.forEach(function(ds,i){ds.data.splice(y, 0, intersect.y)});
   }
})
function getIntersection(){
      var y2=17.68, y1=8.84,x2=2,x1=1,x3 = x1, x4 = x2,
          y4=80,y3=80;
      var x=((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4));
    var y=((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4));
      x = Math.round(x*100)/100;
    y = Math.round(y*100)/100;
    return {x:x,y:y}  ;
}
var myChart = new Chart(ctx, options);
    }

      </script> 
   </head> 
   <body>  
      <canvas id="chart"></canvas> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js" crossorigin="anonymous"></script>   
   </body>
</html>

Related Tutorials