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!