2๐
โ
You can use the onHover
callback in the options to check if the mouse is in the chartArea
if so set the tooltip to enabled else disable the tooltip.
You might want to check also if the value you are setting is already the correct value since it will save a lot of unesesarry updates
Example (V2):
const updateTooltipShow = (chart, enabled) => {
chart.options.tooltips.enabled = enabled;
chart.update();
}
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [1, 2, 3, 4],
datasets: [{
data: [1, 2, 3, 4],
backgroundColor: "rgba(153,255,51,0.6)"
},
]
},
options: {
onHover: function(e, activeElements) {
const {
bottom,
top,
right,
left
} = this.chartArea;
if (e.x >= left && e.x <= right && e.y <= bottom && e.y >= top) {
updateTooltipShow(this, true)
} else {
updateTooltipShow(this, false)
}
},
tooltips: {
mode: 'x',
intersect: false,
callbacks: {
footer: function(tooltipItem, data) {
return 'some text'
}
}
},
}
});
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
Example (V3):
const updateTooltipShow = (chart, enabled) => {
chart.options.plugins.tooltip.enabled = enabled;
chart.update();
}
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [1, 2, 3, 4],
datasets: [{
data: [1, 2, 3, 4],
backgroundColor: "rgba(153,255,51,0.6)"
},
]
},
options: {
onHover: (e, activeElements, chart) => {
const {
bottom,
top,
right,
left
} = chart.chartArea;
if (e.x >= left && e.x <= right && e.y <= bottom && e.y >= top) {
updateTooltipShow(chart, true)
} else {
updateTooltipShow(chart, false)
}
},
plugins: {
tooltip: {
mode: 'x',
intersect: false,
callbacks: {
footer: function(tooltipItem, data) {
return 'some text'
}
}
},
}
}
});
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
0๐
I wrote a simple plugin for hiding the caption when you move your cursor out of the main canvas:
plugins: [{
id: "toolbarHider",
afterEvent: (chart: any, evt: any, opts: any) => {
const { left, right, bottom, top } = chart.chartArea;
const e = evt.event;
const status = e.x >= left && e.x <= right && e.y <= bottom && e.y >= top;
if (status !== chart.options.plugins.tooltip.enabled) {
chart.options.plugins.tooltip.enabled = status;
chart.update();
}
}
}]
More about Chart.js plugins.
Source:stackexchange.com