|
| 1 | +import React, { useEffect } from 'react'; |
| 2 | +import { fabric } from 'fabric'; |
| 3 | +import { v4 as uuidv4 } from 'uuid'; |
| 4 | + |
| 5 | +const DEFAULT_CANVAS_ATTRS: Record<string, number | string | boolean> = { |
| 6 | + uniformScaling: false, |
| 7 | + preserveObjectStacking: true, |
| 8 | + targetFindTolerance: 10, |
| 9 | + // note: currently, canvas group selection only the selection rect with shape bounds. |
| 10 | + // ref: https://github.com/fabricjs/fabric.js/issues/3773 |
| 11 | + // So next best thing is to require user's selection rect to contain the entire object. |
| 12 | + selectionFullyContained: true, |
| 13 | +}; |
| 14 | + |
| 15 | +interface FabricCanvasProps { |
| 16 | + fabricCanvasRef: React.MutableRefObject<fabric.Canvas>; |
| 17 | + width?: number; |
| 18 | + height?: number; |
| 19 | + backgroundColor?: string; |
| 20 | + attrs?: Record<string, number | string | boolean>; |
| 21 | +} |
| 22 | + |
| 23 | +const FabricCanvas: React.FC<FabricCanvasProps> = ({ |
| 24 | + width = 100, |
| 25 | + height = 100, |
| 26 | + backgroundColor = 'green', |
| 27 | + attrs = DEFAULT_CANVAS_ATTRS, |
| 28 | + ...props |
| 29 | +}) => { |
| 30 | + const nativeCanvasRef = React.useRef<HTMLCanvasElement | null>(null); |
| 31 | + |
| 32 | + // canvas resize |
| 33 | + React.useEffect(() => { |
| 34 | + props.fabricCanvasRef.current.setWidth(width); |
| 35 | + props.fabricCanvasRef.current.setHeight(height); |
| 36 | + }, [width, height]); |
| 37 | + |
| 38 | + React.useEffect(() => { |
| 39 | + props.fabricCanvasRef.current.backgroundColor = backgroundColor; |
| 40 | + }, [backgroundColor]); |
| 41 | + |
| 42 | + /** |
| 43 | + * use effect |
| 44 | + */ |
| 45 | + // mount object modify handle |
| 46 | + useEffect(() => { |
| 47 | + if (nativeCanvasRef.current !== null) { |
| 48 | + props.fabricCanvasRef.current = new fabric.Canvas( |
| 49 | + nativeCanvasRef.current.id, |
| 50 | + { |
| 51 | + width, |
| 52 | + height, |
| 53 | + backgroundColor, |
| 54 | + ...attrs, |
| 55 | + }, |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + return () => { |
| 60 | + props.fabricCanvasRef.current?.dispose(); |
| 61 | + }; |
| 62 | + }, []); |
| 63 | + |
| 64 | + return <canvas ref={nativeCanvasRef} id={`canvas_${uuidv4()}`} />; |
| 65 | +}; |
| 66 | + |
| 67 | +export default FabricCanvas; |
0 commit comments