Chartjs-ReactJS – Moving vertical line when hovering over Line chart using chart.js v3.7.1

1👍

You can use a custom plugin for this:

const plugin = {
  id: 'corsair',
  afterInit: (chart) => {
    chart.corsair = {
      x: 0,
      y: 0
    }
  },
  afterEvent: (chart, evt) => {
    const {
      chartArea: {
        top,
        bottom,
        left,
        right
      }
    } = chart;
    const {
      x,
      y
    } = evt.event;
    if (x < left || x > right || y < top || y > bottom) {
      chart.corsair = {
        x,
        y,
        draw: false
      }
      chart.draw();
      return;
    }

    chart.corsair = {
      x,
      y,
      draw: true
    }

    chart.draw();
  },
  afterDatasetsDraw: (chart, _, opts) => {
    const {
      ctx,
      chartArea: {
        top,
        bottom,
        left,
        right
      }
    } = chart;
    const {
      x,
      y,
      draw
    } = chart.corsair;

    if (!draw) {
      return;
    }

    ctx.lineWidth = opts.width || 0;
    ctx.setLineDash(opts.dash || []);
    ctx.strokeStyle = opts.color || 'black'

    ctx.save();
    ctx.beginPath();
    if (opts.vertical) {
      ctx.moveTo(x, bottom);
      ctx.lineTo(x, top);
    }
    if (opts.horizontal) {
      ctx.moveTo(left, y);
      ctx.lineTo(right, y);
    }
    ctx.stroke();
    ctx.restore();
  }
}

Chart.register(plugin)

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      corsair: {
        horizontal: false,
        vertical: true,
        color: 'red',
        dash: [],
        width: 2
      }
    }
  },
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

For you to use this in react, you only need the Chart.register line like so:

import React from "react";
import Chart from 'chart.js/auto';
import { Line } from "react-chartjs-2";
import 'chartjs-adapter-moment';

const plugin = {
  // Plugin code, see stack snipet above
}

Chart.register(plugin)

Leave a comment