How do I add a vertical cursor line in Chart.js?

Viewed 1257

I'd like to add a vertical line following my cursor as I hover over a time series chart in Chart.js. I assume a custom tooltip is the best option for this, but let me know if that's not the case. If it is, I assume interacting with canvas is better than creating a DOM element and repositioning it. Assuming that's the case, I'm stuck on the following code, which I believe is close:

tooltips: {
  mode: 'index',
  intersect: false,
  custom: function (tooltip) {
    const context = chart.chart.ctx
    context.beginPath()
    context.moveTo(tooltip.x, 30)
    context.strokeStyle = '#ff0000'
    context.lineTo(tooltip.x, 340)
    context.closePath()
    context.stroke()
  }
}

This works outside the context of the custom tooltip, ie. from a window.setTimeout, but in the tooltip it does not draw anything. Any advice?

For what it's worth, here's an example I found on another SO post that does what I'm looking for, but I'm assuming putting it in the eventHandler is not recommended?

0 Answers
Related