score:1

Accepted answer
const Component: React.FC = () => {
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const [context, setContext] = React.useState<CanvasRenderingContext2D | null>(
    null
  );

  React.useEffect(() => {
    if (canvasRef.current) {
      const renderCtx = canvasRef.current.getContext('2d');

      if (renderCtx) {
        setContext(renderCtx);
      }
    }
  }, [context]);

  return (
    <div>
      <canvas
        id="canvas"
        ref={canvasRef}
        style={{
          position: 'fixed',
          width: '100%',
          height: '100%'
        }}
      ></canvas>
    </div>
  );

score:1

import { useRef, useEffect } from 'react';

const Background = styled.canvas`
  position: fixed;
  width: 100%;
  height: 100%;
`;

const ComponentUsingTheCanvas = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const context = canvasRef.current.getContext('2d');
    // Do stuff with your canvas context here
  });
  return (
    <Background ref={canvasRef} />
  );
}

Related Query

More Query from same tag