reactjsnext.jsfabricjs

Getting Cannot read properties of null (reading 'clearRect') error in Fabric in Next.js


Getting Cannot read properties of null (reading 'clearRect') error in Fabric.js in Next.js. I am trying to set the background image in fabric.js Canvas. image all set properly but getting the above error with the following code.

import { fabric } from "fabric";
const { fabricObj, canvas, setCanvas, setObjectSelectForDelete } =
    useCanvasContext();
useEffect(() => {
    // 1st init fabric canvas object...
    const initCanvas = new fabric.Canvas(fabricObj?.current, {
        width: "500",
        height: "400",
    });

    fabric.Image.fromURL(
        "https://flowbite.com/docs/images/examples/image-3@2x.jpg",
        function (img) {
            initCanvas.setBackgroundImage(
                img,
                initCanvas.renderAll.bind(initCanvas),
                {
                    scaleX: initCanvas.width / img.width,
                    scaleY: initCanvas.height / img.height,
                },
            );
        },
    );

    setCanvas(initCanvas);

    return () => initCanvas.dispose();
}, []);

i tried to add the code inside try catch block but no success.


Solution

  • You can create a new useEffect to ensure that initCanvas exists, and then set the image. Something like:

      useEffect(() => {
        if (initCanvas) {
         fabric.Image.fromURL(
            "https://flowbite.com/docs/images/examples/image-3@2x.jpg",
            function (img) {
                initCanvas.setBackgroundImage(
                    img,
                    initCanvas.renderAll.bind(initCanvas),
                    {
                        scaleX: initCanvas.width / img.width,
                        scaleY: initCanvas.height / img.height,
                    },
                );
            },
        );
        }
      }, []);