author ChicAboo
 *  date import React , { FC , useEffect , useRef , useCallback , useMemo , memo , HTMLAttributes } from 'react' ; import { prefixCls } from '@/containers/DataFlow' ; import { config , canvasHeight , canvasWidth } from '@/constants/config' ; import { GridTypes } from '@/typings' ; import '@/assets/style/index.scss' ; interface BackgroundProps extends HTMLAttributes < HTMLDivElement > { gridConfig ? : GridTypes ; } const Background = ( { gridConfig , style } ) => { const girdRef = useRef < HTMLCanvasElement > ( null ) ; /**
     *  combine config
     * */ const currentGridConfig = useMemo ( ( ) => { if ( gridConfig && Object . keys ( gridConfig ) . length > 0 ) { return { ... config . grid , ... gridConfig } ; } return config . grid ; } , [ gridConfig ] ) ; /**
     *  draw grid lines
     * */ const drawGridLine = useCallback ( ( x1 , y1 , x2 , y2 ) => { if ( girdRef && girdRef . current ) { const gridCanvas = girdRef . current . getContext ( '2d' ) ; const { strokeWidth , strokeColor , isLineDash , lineDash } = currentGridConfig ; gridCanvas . beginPath ( ) ; gridCanvas . moveTo ( x1 , y1 ) ; gridCanvas . lineTo ( x2 , y2 ) ; if ( isLineDash ) { gridCanvas . setLineDash ( lineDash ) ; } gridCanvas . lineWidth = strokeWidth ; gridCanvas . strokeStyle = strokeColor ; gridCanvas . stroke ( ) ; } } , [ currentGridConfig ] ) ; /**
     * draw grid
     * */ const drawGrid = useCallback ( ( ) => { const distance = currentGridConfig . distance ; const rowNumber = Math . ceil ( canvasHeight / distance ) ; const colNumber = Math . ceil ( canvasWidth / distance ) ; for ( let i = 0 ; i < rowNumber ; i ++ ) { drawGridLine ( 0 , i * distance , canvasWidth , i * distance ) ; } for ( let j = 0 ; j < colNumber ; j ++ ) { drawGridLine ( j * distance , 0 , j * distance , canvasHeight ) ; } } , [ currentGridConfig . distance , drawGridLine ] ) ; useEffect ( ( ) => { drawGrid ( ) ; } , [ drawGrid ] ) ; return ( < div className = { `${ prefixCls }-background` } style = { { ... style } } > < canvas width = { canvasWidth } height = { canvasHeight } ref = { girdRef } / > < /div>); } ; export default memo ( Background ) ;