6
votes

I'm trying to render a vertical line when hovering over the plot area in chartjs v2. I have a basic working version of it but I haven't figured out how to remove the line each time the line is drawn (the old lines just stick around).

Here is a working example - https://jsfiddle.net/s9gyynxp/5/

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    }
});

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

    // Draw the vertical line here
    var eventPosition = Chart.helpers.getRelativePosition(arguments[0], this.chart);
    this.chart.ctx.beginPath();
    this.chart.ctx.moveTo(eventPosition.x, 30);
    this.chart.ctx.strokeStyle = "#ff0000";
    this.chart.ctx.lineTo(eventPosition.x, 340);
    this.chart.ctx.stroke();

    return ret;
};

Note I have seen other solutions to this where a second canvas layer is used on top of the chart canvas - I don't think that is an option for me as I need the vertical line to appear on top of the chart, but below a custom tooltip I will be implementing.

Any suggestions are appreciated, thanks!

2

2 Answers

5
votes

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
votes

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;
};