0

I want to draw a vertical line on hover in ChartJS3 (3.6 to be precise). This used to work in ChartJS2:

// Create vertical line on hover
export class LineWithLine extends LineController {
  draw() {
    // Call line controller method to draw all the points
    super.draw();

    // Get active tooltip
    const tooltip = this.chart['tooltip'];

    if (tooltip._active && tooltip._active.length) {
      var ctx = this.chart.ctx,
        x = tooltip._active[0].element.x,
        topY = this.chart.scales['y'].top,
        bottomY = this.chart.scales['y'].bottom;

      // Draw vertical line
      ctx.save();
      ctx.setLineDash([1, 1]);
      ctx.beginPath();
      ctx.moveTo(x, topY);
      ctx.lineTo(x, bottomY);
      ctx.lineWidth = 1;
      ctx.strokeStyle = '#424242';
      ctx.stroke();
      ctx.restore();
    }
  }
}

But it's not working with 3.6. Has anyone figured this out? I can't find anything on this in their documentation.

EDIT: I tried this approach as well. EDIT2: And it works!

plugins: [{
          afterDraw: (chart) => {
            if (chart.tooltip?._active?.length) {
              const { x } = chart.tooltip._active[0].element;
              const yAxis = chart.scales.y;
              const { ctx } = chart;
              ctx.save();
              ctx.beginPath();
              ctx.moveTo(x, yAxis.top);
              ctx.lineTo(x, yAxis.bottom);
              ctx.lineWidth = 1;
              ctx.strokeStyle = 'rgba(0, 0, 255, 0.4)';
              ctx.stroke();
              ctx.restore();
            }
          },
        }],
Ic3m4n
  • 821
  • 1
  • 11
  • 24
  • Does this answer your question? [Chartjs: Need help on drawing a vertical line when hovering cursor](https://stackoverflow.com/questions/68058199/chartjs-need-help-on-drawing-a-vertical-line-when-hovering-cursor) – LeeLenalee Nov 18 '21 at 11:02
  • @LeeLenalee unfortunately no. There seems to be a change in 3.6 regarding the toolips. – Ic3m4n Nov 18 '21 at 11:30
  • it draws a vertical line as you want right? – LeeLenalee Nov 18 '21 at 11:35
  • If the tooltip is the problem you can just get the active elements using the API method chart.js exposes: https://www.chartjs.org/docs/master/developers/api.html#getelementsateventformode-e-mode-options-usefinalposition – LeeLenalee Nov 18 '21 at 12:23
  • @LeeLenalee Okay, my mistake. This actually works. I had a race condition in my update logic. Thank you! – Ic3m4n Nov 18 '21 at 12:35
  • I'm now using this approach: https://stackoverflow.com/questions/68058199/chartjs-need-help-on-drawing-a-vertical-line-when-hovering-cursor – Ic3m4n Nov 18 '21 at 12:36

0 Answers0