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?
这是基于 timclutton 中的a / 53781749/2358409>此答案,它与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>