admin管理员组

文章数量:1290964

Centering an Image in a Recharts Donut Pie Chart within a Custom Chart Container

I'm using Recharts to create a donut pie chart and I'm trying to center an image in the middle of it. I have a custom ChartContainer component that handles the overall chart layout. I'm running into issues with positioning the image correctly within the pie chart's center.

Problem:

The image isn't consistently centered within the pie chart. It seems the positioning is off. I suspect the issue might be related to how my custom ChartContainer (which is styled with Shadcn UI classes) interacts with Recharts' SVG rendering. Additionally, I tried using the Recharts component to place the image, but it appears is designed for text and doesn't work with image elements.

What I've tried:

Positioning the image absolutely within the ChartContainer using CSS transforms. Using pointerEvents: 'none' to prevent the image from blocking pie chart interactions. Attempting to use the Recharts component (but this doesn't support images).

Here's my code:

import { PieChart, Pie, LabelList } from 'recharts';

function JobMetricPieChart({}) {
  const chartData = [ // Removed useMemo
      { browser: "chrome", visitors: 275, fill: "var(--color-chrome)" },
      { browser: "safari", visitors: 200, fill: "var(--color-safari)" },
    ];

  const chartConfig = {
    visitors: {
      label: "Visitors",
    },
    chrome: {
      label: "Chrome",
      color: "var(--chart-2)",
    },
    safari: {
      label: "Safari",
      color: "var(--chart-2)",
    },
  }; // Removed satisfies

  return (
    <ChartContainer config={chartConfig} className="relative">
      <PieChart> {/* Removed ref */}
        <Pie data={chartData} dataKey="visitors" innerRadius="50%" paddingAngle={3} cornerRadius={5} stroke="var(--border)">
          <LabelList dataKey="visitors" className="fill-background" stroke="var(--foreground)" fontFamily="var(--font-sans)" fontSize={12} formatter={(value) => `${value.toString()}%`} />
        </Pie>
      </PieChart>

      <div className="absolute" style={{ 
        left: '50%', // Center horizontally
        top: '50%', // Center vertically
        transform: 'translate(-50%, -50%)', // Key for perfect centering
        pointerEvents: 'none' 
       }}>
        <Image src="/helmet.svg" width={35} height={35} alt="" />
      </div>
    </ChartContainer>
  );
}

export default JobMetricPieChart;

本文标签: typescriptCentering an Image in a Recharts (ShadCn) Donut Pie ChartStack Overflow