0

I want to display the chart image rather than the chart from react-chartjs-2 and chart.js.

However, the image is never fully rendered at first

export function App() {
  const chartRef = useRef<ChartJS>(null);
  const [chartImg, setChartImg] = useState<string>();

  const ChartRef = () => <Chart ref={chartRef} type="line" data={data} />;
  useEffect(() => {
    const chart = chartRef.current;
    if (!chart) return;
    const img = chart.toBase64Image(); // just white background
    setChartImg(img);
  }, []);

  const showImage = useCallback(() => {
    const chart = chartRef.current;
    if (!chartRef.current) return;
    const img = chart.toBase64Image(); // Correct image is displayed
    setChartImg(img);
  }, []);
  return (
    <div>
      <ChartRef />
      <button type="button" onClick={showImage}>
        Display Image
      </button>
      <img src={chartImg} alt="here" />
    </div>
  );
}

In the following code (linked codesandbox here), the image is not displayed until I click on the Display Image button.

Is there any way I can run an initial check on useEffect and make sure the image is correctly displayed instead of chart without having to click on Display Image for example?

Saad Bahir
  • 159
  • 2
  • 9
  • You could implement a plugin, using "afterRender" hook. https://codesandbox.io/s/nifty-bartik-z10mrl Or you could use "animation.onComplete" callback if animation is enabled – user2057925 Sep 01 '22 at 13:35

1 Answers1

1

This is because you are trying to read the canvas before the ami,mations and draws are finished, you either need to set the animations to false or use the onAnimationComplete callback:

options: {
  animations: false
}
options: {
  animations: {
    onComplete: ({initial}) => {
      if (initial) savechart();
    }
  }
}
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69