Skip to content

Instantly share code, notes, and snippets.

@RoxasShadow
Created October 26, 2019 14:16
Show Gist options
  • Save RoxasShadow/83c8f22a8d523d105ab58e4acae3c139 to your computer and use it in GitHub Desktop.
Save RoxasShadow/83c8f22a8d523d105ab58e4acae3c139 to your computer and use it in GitHub Desktop.
Draw cross lines when hovering on a Chart.js graph.
Chart.defaults.LineWithLine = Chart.defaults.line;
Chart.controllers.LineWithLine = Chart.controllers.line.extend({
draw: function(ease) {
Chart.controllers.line.prototype.draw.call(this, ease);
if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
var activePoint = this.chart.tooltip._active[0],
ctx = this.chart.ctx,
x = activePoint.tooltipPosition().x,
y = activePoint.tooltipPosition().y,
chartY = this.chart.scales['y-axis-0'],
chartX = this.chart.scales['x-axis-0'],
color = '#757575';
// draw vertical line
ctx.save();
ctx.beginPath();
ctx.moveTo(x, chartY.top);
ctx.lineTo(x, chartY.bottom);
ctx.lineWidth = 1;
ctx.strokeStyle = color;
ctx.stroke();
ctx.restore();
// draw horizontal line
ctx.save();
ctx.beginPath();
ctx.moveTo(chartX.left, y);
ctx.lineTo(chartX.right, y);
ctx.lineWidth = 1;
ctx.strokeStyle = color;
ctx.stroke();
ctx.restore();
}
}
});
/* USAGE */
new Chart(ctx, {
type: 'LineWithLine',
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment