如何在图例悬停时显示工具提示?

问题描述

我在 React 中使用 chart.js。

我已阅读并实施: Chart.js - show tooltip when hovering on legend

不幸的是,这并没有提供预期的结果。我相信这是因为这是在 javascript 中实现的,而我正在实现 react。不确定这是否会影响任何事情。

const data = {
    labels: ['One','Two','Three'],datasets: [{
      data: [4,5,3],backgroundColor: ['rgba(255,99,132,0.2)','rgba(255,159,64,'rgba(54,162,235,0.2)'],borderColor: ['rgb(255,132)','rgb(255,64)','rgb(54,235)'],hoverBackgroundColor: ['rgba(255,0.4)',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,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();
        }
      },},}

此组件的结尾返回以下内容

return <Doughnut data={data} options={options} />;

这会生成链接的 stackoverflow 帖子中显示的图表。

解决方法

对于 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();
        },