Search code examples
javascriptvue.jschart.jsvue-chartjs

ChartJS: Draw line between two data points on hover


enter image description here

Hi everyone, I have created the chart shown in the image.

Does anyone know how to draw a line between dataset of same index when trying to hover on either data (the red line).

I'm using ChartJS on VueJS component


Solution

  • The Plugin Core API offers a range of hooks that may be used for performing custom code. You can draw the line directly on the canvas using CanvasRenderingContext2D.stroke().

    In below code snippet, I use the afterDraw hook and draw the line in case the tooltip would be shown otherwise. Please consult addPlugin from vue-chart.js documentation to learn how to add such inline plugin in Vue.js.

    var chart = new Chart('canvas', {
      type: 'line',
      plugins: [{
        afterDraw: chart => {
          if (chart.tooltip._active && chart.tooltip._active.length) {
            const ctx = chart.ctx;
            ctx.save();
            const activePoint = chart.tooltip._active[0];
            const x = activePoint.tooltipPosition().x; 
            const yAxis = chart.scales['y-axis-0'];
            const value1 = chart.data.datasets[0].data[activePoint._index];
            const value2 = chart.data.datasets[1].data[activePoint._index];
            const y1 = yAxis.getPixelForValue(value1);
            const y2 = yAxis.getPixelForValue(value2);
            ctx.beginPath();
            ctx.moveTo(x, y1);
            ctx.lineTo(x, y2);
            ctx.lineWidth = 2;
            ctx.strokeStyle = 'green';
            ctx.stroke();
            ctx.restore();
          }
        }
      }],
      data: {
        labels: ['A', 'B', 'C', 'D', 'E', 'F'],
        datasets: [{
            data: [13, 10, 12, 13, 9, 12],
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgb(255, 99, 132)',
            fill: false
          },
          {
            data: [10, 7, 9, 10, 6, 9],
            backgroundColor: 'rgba(255, 159, 64, 0.2)',
            borderColor: 'rgb(255, 159, 64)'
          }
        ]
      },
      options: {
        legend: {
          display: false
        },
        tooltips: {
          enabled: false
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <canvas id="canvas" height="90"></canvas>