How to show text inside line point onhover #10742
Answered
by
kurkle
DiegoMcDipster
asked this question in
Q&A
-
Hi, I'm new to Chartjs and so far it seems like an excellent package! I have a line chart. What I would like to do is:
So, all I'm missing is how to get the value or any string to be displayed when i hover over the point. |
Beta Was this translation helpful? Give feedback.
Answered by
kurkle
Oct 4, 2022
Replies: 1 comment 1 reply
-
You could use the datalabels plugin, or you can do the drawing by your own plugin in For example: 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]
}]
},
options: {
hoverRadius: 30,
plugins: {
tooltip: false
}
},
plugins: [{
id: 'hoverValue',
afterDraw(chart) {
chart.getActiveElements().forEach((active) => drawTextInPoint(chart, active));
}
}]
});
function drawTextInPoint(chart, {element, datasetIndex, index}) {
const value = chart.data.datasets[datasetIndex].data[index];
const ctx = chart.ctx;
const {radius} = element.options
const fontSize = ~~radius
ctx.save();
ctx.font = `${fontSize}px times`
ctx.fillStyle = 'red'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(value, element.x, element.y + radius/15)
ctx.restore();
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
DiegoMcDipster
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could use the datalabels plugin, or you can do the drawing by your own plugin in
afterDraw
orafterDatasetDraw
hook. More information about plugins: https://www.chartjs.org/docs/latest/developers/plugins.htmlFor example: