Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React + fabric.js

I am trying to combine react and fabricjs but I am stuck.

Here is my code

import React, { useState, useEffect, useRef  } from 'react';
import { fabric } from "fabric";

function App() {

  const [canvas, setCanvas] = useState('');

  useEffect(() => {
    setCanvas(initCanvas());
    
  }, []);

  const initCanvas = () => (
    new fabric.Canvas('canvas', {
      height: 800,
      width: 800,
      backgroundColor: 'pink' ,
      selection: false,
      renderOnAddRemove: true,
     
    })

  )

    canvas.on("mouse:over", ()=>{
      console.log('hello')
    })


  return (

    <div >
      <canvas id="canvas" />
    </div>

  );
}

export default App;

The problem is canvas.on as it causes the error 'Uncaught TypeError: canvas.on is not a function' Please tell me what am I doing wrong here

like image 418
Seweryn Woźniak Avatar asked Sep 07 '26 14:09

Seweryn Woźniak


1 Answers

Actually the problem is that you trying to call canvas.on when it is an empty string in canvas (initial state)

Since we are only need to create fabric.Canvas once, I would recommend to store instance with React.useRef

I created an example for you here:

--> https://codesandbox.io/s/late-cloud-ed5r6q?file=/src/FabricExample.js

Will also show the source of the example component here:

import React from "react";
import { fabric } from "fabric";

const FabricExample = () => {
  const fabricRef = React.useRef(null);
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const initFabric = () => {
      fabricRef.current = new fabric.Canvas(canvasRef.current);
    };

    const addRectangle = () => {
      const rect = new fabric.Rect({
        top: 50,
        left: 50,
        width: 50,
        height: 50,
        fill: "red"
      });

      fabricRef.current.add(rect);
    };

    const disposeFabric = () => {
      fabricRef.current.dispose();
    };

    initFabric();
    addRectangle();

    return () => {
      disposeFabric();
    };
  }, []);

  return <canvas ref={canvasRef} />;
};

export default FabricExample;

like image 133
kerm Avatar answered Sep 12 '26 20:09

kerm