Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { forwardRef, type LegacyRef, useEffect, useRef } from "react";
 
interface VirtualCanvasProps {
  width: number;
  height: number;
}
 
export const VirtualCanvas = forwardRef<HTMLCanvasElement, VirtualCanvasProps>((props, ref) => {
  const rootRef = useRef<HTMLDivElement>();
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
 
  const attachRef = (canvas: HTMLCanvasElement | null) => {
    if (ref instanceof Function) {
      ref(canvas);
    } else if (ref) {
      ref.current = canvas;
    }
  };
 
  useEffect(() => {
    const canvas = document.createElement("canvas");
 
    canvas.width = props.width;
    canvas.height = props.height;
    canvas.style.background = "transparent";
 
    canvasRef.current = canvas;
    rootRef.current?.appendChild(canvas);
 
    attachRef(canvasRef.current);
  }, []);
 
  useEffect(() => {
    if (canvasRef.current) {
      canvasRef.current.width = props.width;
      canvasRef.current.height = props.height;
    }
  }, [props.width, props.height]);
 
  useEffect(
    () => () => {
      const canvas = canvasRef.current!;
      const ctx = canvas.getContext("2d");
 
      ctx?.clearRect(0, 0, canvas.width, canvas.height);
      canvas.remove();
      canvasRef.current = null;
      attachRef(null);
    },
    [],
  );
 
  return <div ref={rootRef as LegacyRef<HTMLDivElement>} />;
});