File size: 763 Bytes
75fefa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { debounce } from "lodash-es";

export default (canvas: HTMLCanvasElement) => {
  const { width, height } = canvas.getBoundingClientRect();
  const ctx = canvas.getContext("2d")!;

  canvas.style.width = `${width}px`;
  canvas.style.height = `${height}px`;

  const upscaleCanvas = () => {
    const scale = window.visualViewport?.scale || 1;
    const dpr = (window.devicePixelRatio || 1) * scale;

    canvas.width = width * dpr;
    canvas.height = height * dpr;

    ctx.scale(dpr, dpr);

    canvas.dispatchEvent(new Event("resize"));
  };

  upscaleCanvas();

  const handleResize = debounce(upscaleCanvas, 500);

  window.addEventListener("resize", handleResize);
  window.visualViewport?.addEventListener("resize", handleResize);

  return ctx;
};