0

I've been struggling for a while on this. I am using React with Fabric js and I am trying to resize / move an image a user uploaded. I also want to resize / move a shape I created as well. It unfortunately does not do that. In the other hand if I get an image straight from the url, it works. What am I doing wrong? Here is a simplified code example:

  function App() {
  const [canvas, setCanvas] = useState(null);
  const handleFileUpload = (e) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      const image = new Image();
      image.src = e.target.result;
      image.onload = function () {
        const img = new fabric.Image(image);
        canvas.add(img).setActiveObject(img).renderAll();
      };
    };
    reader.readAsDataURL(e.target.files[0]);
  };

  useLayoutEffect(() => {
    const initCanvas = () =>
      new fabric.Canvas("c", {
        height: 800,
        width: 800,
      });
    setCanvas(initCanvas());
  }, []);

  const addRect = () => {
    const rect = new fabric.Rect();
    rect.set({
      height: 100,
      width: 100,
      fill: "red",
    });
    canvas.add(rect).setActiveObject(rect).renderAll();
  };

  return (
    <div className="App">
      <canvas id="c" />
      <button onClick={addRect}>Rectangle</button>
      <input
        type="file"
        accept=".doc,.ppt,.pdf,.mp4,image/*"
        id="cameraInput"
        name="cameraInput"
        onChange={(e) => handleFileUpload(e)}
      />
    </div>
  );
}

Here is also a demo

user9638389
  • 17
  • 1
  • 8

1 Answers1

2

I think this issue has something to do with React - strict mode.

  <StrictMode>
    <App />
  </StrictMode>

https://reactjs.org/docs/strict-mode.html

Here is the demo with a similar code as the demo shared in the question but without strictmode.

Demo-without strict mode

A.D
  • 356
  • 4
  • 17
  • You have any idea why? – user9638389 Aug 03 '22 at 03:53
  • Not sure about it, but may be strict mode treats fabric events handling as a side effect as it is a third-party library. I would suggest you to try lifecycle-based approach https://stackoverflow.com/questions/37565041/how-can-i-use-fabric-js-with-react/39186522#39186522 – A.D Aug 03 '22 at 08:49