[英]How to show tooltip on legend hover?
I am using chart.js in React.我在 React 中使用 chart.js。
I have read and implemented: Chart.js - show tooltip when hovering on legend我已阅读并实施: Chart.js - 悬停在图例上时显示工具提示
Unfortunately, this is not providing the desired results.不幸的是,这并没有提供预期的结果。 I believe this is because this is being implemented in javascript, and I am implementing react.我相信这是因为这是在 javascript 中实现的,而我正在实现 react。 Not sure if that is impacting anything.不确定这是否会影响任何事情。
const 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
}]
};
const options = {
plugins: {
legend: {
onHover: (evt: any, legendItem: any, legend: any) => {
const index = legend.chart.data.labels.indexOf(legendItem.text);
const activeSegment = legend.chart.getDatasetMeta(0).data[index];
// console.log(activeSegment);
// activeSegment.options.backgroundColor = activeSegment._options.hoverBackgroundColor;
// activeSegment.options.borderWidth = activeSegment._options.hoverBorderWidth;
legend.chart.tooltip._active = [activeSegment];
legend.chart.update();
legend.chart.draw();
},
onLeave: (evt: any, legendItem: any, legend: any) => {
const index = legend.chart.data.labels.indexOf(legendItem.text);
// const activeSegment = legend.chart.getDatasetMeta(0).data[index];
// activeSegment.options.backgroundColor = activeSegment._options.backgroundColor;
// activeSegment.options.borderWidth = activeSegment._options.borderWidth;
legend.chart.tooltip._active = [];
legend.chart.update();
legend.chart.draw();
}
},
},
}
with the end of this component returning the following:此组件的结尾返回以下内容:
return <Doughnut data={data} options={options} />;
This produces the chart that is shown in the stackoverflow post that I linked.这会生成我链接的 stackoverflow 帖子中显示的图表。
For v3 you can use an method to set the tooltip programatically对于 v3,您可以使用一种方法以编程方式设置工具提示
onHover: (evt, item, legend) => {
const chart = legend.chart;
const tooltip = chart.tooltip;
const chartArea = chart.chartArea;
tooltip.setActiveElements([{
datasetIndex: 0,
index: item.index,
}], {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
chart.update();
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.