Reputation: 734
I create a FabricJS object in a context provider and store it into the context:
const [canvas, setCanvas] = useState(false);
const initCanvas = (c) => {
setCanvas(new fabric.Canvas(c));
console.log('Canvas initialized', canvas);
}
When the canvas component has mounted, I call this initCanvas() function.
useEffect(() => {
context.initCanvas('c');
}, []);
FabricJS offers an event listener with a variety of events to listen to. For instance canvas.on('object:added', handler) gets fired when an object gets added to the canvas. I want to use canvas.getObjects() method from Fabric to update the object list into the context
useEffect(() => {
if(canvas) {
setObjectList(canvas.getObjects());
}
console.log("ObjectList:", objectList);
}, [canvas]); //??
How can I update a ReactJS component, when an event happens in Fabric?
Upvotes: 2
Views: 737
Reputation: 2351
useEffect(()=> {
if (!canvas) {return;}
function handleChange(){
setObjectList(canvas.getObjects());
}
handleChange(); // initialize
canvas.on("object:added", handleChange);
return ()=> {
canvas.off("object:added");
}
}, [canvas])
Upvotes: 2