๐:0
You will need a custom plugin for this, see live example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'red',
backgroundColor: 'red'
}]
},
options: {
plugins: {
selector: {
color: 'blue',
width: 2,
// If canvas has a different backgroundColor set this to match
boxColor: 'white'
}
}
},
plugins: [{
id: 'selector',
beforeDatasetsDraw: (chart, args, opts) => {
// Return if no hover
if (chart._active.length === 0) {
return;
}
// Set all variables needed
const activeEl = chart._active[0].element;
const labelItem = chart.scales.x._labelItems[chart._active[0].index];
const {
ctx,
scales: {
y
}
} = chart;
const metrics = ctx.measureText(labelItem.label);
const labelWidth = metrics.width;
const labelHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;
// Draw white box over old label
ctx.save();
ctx.fillStyle = opts.boxColor || '#FFFFFF';
ctx.fillRect((labelItem.translation[0] - labelWidth / 2), labelItem.translation[1], labelWidth, labelHeight);
ctx.restore();
// Draw new text on canvas
ctx.save();
ctx.font = Chart.helpers.toFontString(Object.assign(labelItem.font, {
style: 'bold'
}));
ctx.fillText(labelItem.label, (labelItem.translation[0] - labelWidth / 2), labelItem.translation[1] + labelItem.textOffset)
ctx.restore();
// Draw vertical line down from point
ctx.save();
ctx.lineWidth = opts.width || 1;
ctx.strokeStyle = opts.color || 'black';
ctx.beginPath();
ctx.moveTo(activeEl.x, activeEl.y);
ctx.lineTo(activeEl.x, y.getPixelForValue(y.min));
ctx.stroke();
ctx.restore();
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
</body>