首页 > 解决方案 > 如何使工具提示跟随饼图中的光标?

问题描述

如何使工具提示跟随使用 recharts 制作的饼图中的光标?

目前,会显示一个工具提示,但它只是停留在某个位置,直到光标直接移动到该位置。我需要的是一个随光标移动的工具提示。我可以在一个特定的位置可能在图表的顶部或任何东西。

演示:https ://jsfiddle.net/kg7Ldj1o/

我需要径向条形图中显示的类似内容。http://recharts.org/en-US/api/RadialBarChart 此处工具提示随光标移动。

<PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
  <Tooltip />
  <Pie
    data={data}
    cx={420}
    cy={200}
    startAngle={180}
    endAngle={0}
    cornerRadius={40}
    innerRadius={60}
    outerRadius={80}
    fill="#8884d8"
    paddingAngle={-15}
  >
    {data.map((entry, index) => (
      <Cell
        fill={
          index === 0 || index === data.length - 1
            ? COLORS[index % COLORS.length]
            : 'transparent'
        }
        stroke={
          index === 0 || index === data.length - 1
            ? COLORS[index % COLORS.length]
            : 'transparent'
        }
      />
    ))}
  </Pie>
  <Pie
    data={data}
    cx={420}
    cy={200}
    startAngle={180}
    endAngle={0}
    cornerRadius={0}
    innerRadius={60}
    outerRadius={80}
    fill="#8884d8"
  >
    {data.map((entry, index) => (
      <Cell
        fill={
          index === 0 || index === data.length - 1
            ? 'transparent'
            : COLORS[index % COLORS.length]
        }
        stroke={
          index === 0 || index === data.length - 1
            ? 'transparent'
            : COLORS[index % COLORS.length]
        }
      />
    ))}
  </Pie>
</PieChart>;

标签: reactjsrecharts

解决方案


您可以使用事件中提供的 chartX 和 chartY来监听onMouseMove和更新元素的左上角偏移量。.recharts-tooltip-wrapper

演示jsfiddle 链接

我添加了onPieEnter如下功能,

onPieEnter(e){
    console.log(e);
    if(e){
      let toolTipWrapper = document.getElementsByClassName("recharts-tooltip-wrapper")[0];
      toolTipWrapper.style.transition = 'transform 400ms ease 0s';
      toolTipWrapper.style.transform = "translate("+ (e.chartX + 10) +"px, "+ (e.chartY + 10) +"px)";
    }
}

推荐阅读