'Canvas toBlob generates empty image with react-pixi

I am using react-pixi to generate some content on canvas

At some stage, I want to save the generated image to an image file

Here's my component (abbreviated)

const FramePreview = ({...}) => {
  const ref = useRef();

  useEffect(() => {
    if (saveCanvasAsImage && canvasWidthPX && canvasHeightPX) {
      ref.current._canvas?.toBlob(blob => {
        const fileName = 'canvas.png';

        const file = new File([blob], fileName, {
          type: 'image/png',
        });

        const formData = new FormData();
        formData.append('file', file, fileName);
        formData.append('name', fileName);
        formData.append('uuid', uuid());

        axios.post(route('media-library-uploads'), formData, {
          headers: {
            'accept': 'application/json',
            'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
          },
        }).then(({data}) => {
          setRenderedArtwork(data);
        });
      }, 'image/png');
    }
  }, [canvasWidthPX, canvasHeightPX, saveCanvasAsImage]);

  return (canvasWidthPX && canvasHeightPX && (
    <div>
      <Stage height={canvasHeightPX} width={canvasWidthPX} className="w-full max-w-full" ref={ref}>
        [content of the canvas]
      </Stage>
    </div>
  ) || <>Loading</>);
};

The problem is that whatever technique I use to retrieve the canvas element or whatever method I use to generate the image from it, it always gives me a completely transparent PNG with the correct dimensions.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source