reactchartjs / react-chartjs-2

React components for Chart.js, the most popular charting library
https://react-chartjs-2.js.org
MIT License
6.58k stars 2.37k forks source link

[Bug]: Re-rendered multiple time while using afterDraw #1215

Open LittleCuong opened 3 months ago

LittleCuong commented 3 months ago

Would you like to work on a fix?

Current and expected behavior

I am making a stacked bar chart with label text is replaced with image but my handleDrawImage runs multiple times in the first-time component render and hovering to display tooltip that causing performance issue

   const handleDrawImage = (chart: ChartJS) => {
    const { ctx } = chart;
    const dataLength = plans ? plans.length : 0;
    const chartHeight = chart.chartArea.height;
    const step = (chartHeight - barSize * dataLength) / dataLength;
    const yOffset = 30;
    ctx.save();
    plans?.forEach((item, i) => {
        let newImage = new Image();
        newImage.src = "Image source here";
        const imageY = i * (barSize + step) + yOffset;
        ctx.drawImage(newImage, 0, imageY, 30, 30);
    });
    ctx.restore();
 };

 return (
    <div className="col-span-9">
        <div className="w-full flex items-center justify-center">
            <Bar
                data={data}
                height={400}
                options={chartOptions}
                redraw={true}
                plugins={[
                    {
                        id: 'sectorBackground',
                        afterDraw: (chart) => handleDrawImage(chart),
                    },
                    ChartDataLabels,
                ]}
            />
        </div>
    </div>
 );

Reproduction

N/A

chart.js version

"^4.4.3"

react-chartjs-2 version

"^5.2.0"

Possible solution

No response