How can I use Fabric.js with React?

后端 未结 5 546
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 15:31

I have an application using heavily HTML5 canvas via Fabric.js. The app is written on top of Angular 1.x, and I am planning to migrate it to React. My app allows writing tex

5条回答
  •  情书的邮戳
    2020-12-04 15:59

    With react 16.8 or newer you can also create a custom hook:

    import React, { useRef, useCallback } from 'react';
    const useFabric = (onChange) => {
        const fabricRef = useRef();
        const disposeRef = useRef();
        return useCallback((node) => {
            if (node) {
                fabricRef.current = new fabric.Canvas(node);
                if (onChange) {
                    disposeRef.current = onChange(fabricRef.current);
                }
            }
            else if (fabricRef.current) {
                fabricRef.current.dispose();
                if (disposeRef.current) {
                    disposeRef.current();
                    disposeRef.current = undefined;
                }
            }
        }, []);
    };
    

    Usage

    const FabricDemo = () => {
      const ref = useFabric((fabricCanvas) => {
        console.log(fabricCanvas)
      });
      return 
    }

提交回复
热议问题