I am using Fabric js inside my react project ( I did that by following this concept). And I used createContext
to fetch the canvas that is been created. There is a Property window component which is going to check what object is selected in the canvas. Initially, there is no canvas. It is created when the user imports an image. I was planning that there will be a useState variable
, which will change whenever new object of canvas is selected.
Objective is similar to Fabricjs Kitchensink
import { fabric } from "fabric";
import { useContext, useEffect, useState } from "react";
import { FabricContext } from "../../App";
export const PropertyWindow = () => {
let canvas = useContext(FabricContext);
// when the canvas will be created then canvas.current will point to `fabric.Canvas`
let [selectedObject, setSelectedObject] = useState();
return (
<div>{/* Here I will add the styles of that selected object. */}</div>
);
};
Here in this code I wanted to store the selected object inside selectedObject
and also the value will change whenever a new object is created
Firstly I planned to create a function that will trigger whenever the canvas is created, for this
I used useEffect
(like this: useEffect(() => {},[canvas])
) with useState
, but it was not working (I was printing the canvas, and in the console it was showing null
and that was when the page was loaded ). Later, my approach was to use useEffect
in the parent component and send the canvas as a prop, here also it was showing the same thing.
Right now I am planning for classic javascript approach to solve this problem. I will be using setInterval
like this
setInterval(()=>{
if(canvas.current?.getSelectedObject() !== null){
setSelectedObject(canvas.current.getSelectedObject()
}
}, 300);
This will check inside the canvas if there is any object selected every 300ms and if there is selected then it will change the useState variable
.
I have not used it yet, and I think there is a better way to fix this problem. I am not sure how to even search for this problem over the internet since this is problem is too specific.