Cannot read properties of null (reading 'clearRect')
错误。我正在尝试在 Fabric.js Canvas 中设置背景图像。图像全部设置正确,但使用以下代码出现上述错误。
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/[email protected]",
function (img) {
initCanvas.setBackgroundImage(
img,
initCanvas.renderAll.bind(initCanvas),
{
scaleX: initCanvas.width / img.width,
scaleY: initCanvas.height / img.height,
},
);
},
);
setCanvas(initCanvas);
return () => initCanvas.dispose();
}, []);
我尝试在 try catch 块中添加代码,但没有成功。
useEffect(() => {
if (initCanvas) {
fabric.Image.fromURL(
"https://flowbite.com/docs/images/examples/[email protected]",
function (img) {
initCanvas.setBackgroundImage(
img,
initCanvas.renderAll.bind(initCanvas),
{
scaleX: initCanvas.width / img.width,
scaleY: initCanvas.height / img.height,
},
);
},
);
}
}, []);