# All files / utils useCanvas.ts

88.89% Statements 8/9
50% Branches 2/4
100% Functions 2/2
88.89% Lines 8/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    251x
    1x

    1x

    9x

    9x
    6x

    6x
    6x

     import {useLayoutEffect, DependencyList, MutableRefObject} from 'react'
    import {clearCanvas} from '../utils/clearCanvas'

    export const useCanvas = (
      canvasRef: MutableRefObject<HTMLCanvasElement>,
      width: number,
      height: number,
      renderFunction: (context: CanvasRenderingContext2D) => void,
      renderFunctionDeps?: DependencyList
    ): void => {
      const deps = renderFunctionDeps
        ? [canvasRef.current, width, height, ...renderFunctionDeps]
        : null

      // TODO: Resize canvas immediately on width/height change but debounce drawing
      useLayoutEffect(() => {
        Iif (!canvasRef.current) {
          return
        }

        clearCanvas(canvasRef.current, width, height)
        renderFunction(canvasRef.current.getContext('2d'))
      }, deps)
    }