Skip to content

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

@LittleCuong

Description

@LittleCuong

Would you like to work on a fix?

  • Check this if you would like to implement a PR, we are more than happy to help you go through the process.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions