[Chartjs]-How to render a vertical line on hover in chartjs

5👍

Just add the following lines before you draw your line

...
this.clear();
this.draw();
...

By the way, your line doesn’t stretch all the way to the bottom. If you want to make it stretch all the way down use 0 and this.chart.height for your yStart and yEnd. Or you can use the y axis scale to calculate the max and min pixels for the scale (see https://jsfiddle.net/ombaww9t/).


Fiddle – https://jsfiddle.net/56s9av1j/

5👍

Working version for 2.6.0 (change ‘y-axis-0’ to the id of you y-axis)

// Hook into main event handler
let parentEventHandler = Chart.Controller.prototype.eventHandler;
Chart.Controller.prototype.eventHandler = function () {
    let ret = parentEventHandler.apply(this, arguments);

    let x = arguments[0].x;
    let y = arguments[0].y;
    this.clear();
    this.draw();
    let yScale = this.scales['y-axis-0'];
    this.chart.ctx.beginPath();
    this.chart.ctx.moveTo(x, yScale.getPixelForValue(yScale.max));
    this.chart.ctx.strokeStyle = "#ff0000";
    this.chart.ctx.lineTo(x, yScale.getPixelForValue(yScale.min));
    this.chart.ctx.stroke();

    return ret;
};

Leave a comment