0

I am using fabric.js library in my react app.
https://www.npmjs.com/package/fabric

I am adding a simple yellow rectangle on the canvas using fabric. The rectangle shows correctly on the canvas in yellow colour. That is OK. But I want to move it (drag it) also. I am unable to move/ drag the yellow rectangle. Please help.

import React, { useState, useEffect } from "react";
import { fabric } from "fabric";
import "./App.css";
const App = () => {
  const [canvas, setCanvas] = useState("");
  useEffect(() => {
    setCanvas(initCanvas());
  }, []);
  const initCanvas = () =>
    new fabric.Canvas("canvas", {
      height: 800,
      width: 800,
      backgroundColor: "lightgray",
      selection: true
    });

  const addRect = (canvi) => {
    const rect = new fabric.Rect({
      height: 280,
      width: 200,
      fill: "yellow",
      selectable: true
    });
    canvi.add(rect);
    canvi.renderAll();
  };

  return (
    <div>
      <h1>Fabric.js on React - fabric.Canvas('...')</h1>
      <button onClick={() => addRect(canvas)}>Rectangle</button>
      <canvas id="canvas" />
    </div>
  );
};

export default App;

This is the tutorial that I am following:
https://aprilescobar.medium.com/part-1-fabric-js-on-react-fabric-canvas-e4094e4d0304

NightCoder101
  • 143
  • 3
  • 12
  • Could be related to this question about strict mode https://stackoverflow.com/a/73205557/5646527 – A.D Apr 10 '23 at 12:54

1 Answers1

1

Had the same issue, for me it was resolved by removing the strictmode tags in main.jsx which interfered with Fabric.js - now it works perfectly <React.StrictMode> </React.StrictMode>

marti
  • 11
  • 2