Chart.js - 悬停在图例上时显示工具提示
我最近将我的 Chart.js 版本从 v2.3
升级到 v2.7.1
,这破坏了现有的功能,即圆环图中的指定段将是当用户将鼠标悬停在相应的图例项上时处于活动状态(悬停颜色,显示工具提示).该代码如下所示:
I recently upgraded my version of Chart.js from v2.3
to v2.7.1
, which broke an existing functionality where the specified segment in a doughnut chart would be active (hover color, tooltip shown) when the user hovered over the corresponding legend item. That code looked like this:
var " + ClientID + @" = new Chart(" + ClientID + @"CTX, {
data: { ... },
options: {
legend: {
onHover: function(evt, legendItem) {
var index = " + ClientID + @".data.labels.indexOf(legendItem.text);
if (" + ClientID + @".data.datasets[0].data[index] > 0) {
var metaData = " + ClientID + @".getDatasetMeta(0);
var activeSegment = metaData.data[index];
" + ClientID + @".tooltipActive = [activeSegment];
" + ClientID + @".active = [activeSegment];
}
},
}
}
});
查看 Chart.js 文件和文档,似乎 tooltipActive
属性已被完全删除,从而破坏了图例悬停功能.我查看了 Chart.js git 上的发行说明和 PR,但不能找到将其标记为重大更改的地方,或任何提及它的地方.我必须升级 Chart.js 的版本才能进行单独的更改,因此不能选择恢复到 v2.3
.有没有其他人遇到过这种情况?
Looking through the Chart.js file and documentation, it looks like the tooltipActive
property has been completely removed, thus breaking the legend hover functionality. I looked through the release notes and PRs on the Chart.js git but couldn't find where this was noted as a breaking change, or any mention of it whatsoever. I have to upgrade versions of Chart.js for a separate change I'm making, so reverting back to v2.3
is not an option. Has anyone else run into this?
推荐答案
这是一个基于 this anwser 的解决方案,来自 timclutton 适用于当前版本的 Chart.js (2.9.3).
Here's a solution based on this anwser from timclutton that works with the current version of Chart.js (2.9.3).
const chart = new Chart('chart', {
type: 'doughnut',
data: {
labels: ['One', 'Two', 'Three'],
datasets: [{
data: [4, 5, 3],
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
borderWidth: 1,
hoverBorderWidth: 3
}]
},
options: {
legend: {
onHover: (evt, legendItem) => {
const index = chart.data.labels.indexOf(legendItem.text);
const rect = chart.canvas.getBoundingClientRect();
const point = chart.getDatasetMeta(0).data[index].getCenterPoint();
const e = new MouseEvent('mousemove', {
clientX: rect.left + point.x,
clientY: rect.top + point.y
});
chart.canvas.dispatchEvent(e);
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="80"></canvas>
相关文章