6👍
✅
Attach your plugin to the afterDatasetDraw
hook, instead of afterDraw
. This will make the horizontal line to be drawn before the tooltip.
var horizonalLinePlugin = {
afterDatasetDraw: function(chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index, line, style, width;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
style = (line.style) ? line.style : "rgba(169,169,169, .6)";
yValue = (line.y) ? yScale.getPixelForValue(line.y) : 0;
ctx.lineWidth = (line.width) ? line.width : 3;
if (yValue) {
ctx.beginPath();
ctx.moveTo(chartInstance.chartArea.left, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
}
}
};
Chart.pluginService.register(horizonalLinePlugin);
new Chart(canvas, {
type: 'bar',
data: {
labels: ["January", "February"],
datasets: [{
label: "Dataset 1",
data: [80, 50]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
horizontalLine: [{
y: 50,
style: 'red'
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
Source:stackexchange.com