-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathascii-background.tsx
More file actions
45 lines (35 loc) · 1.18 KB
/
Copy pathascii-background.tsx
File metadata and controls
45 lines (35 loc) · 1.18 KB
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
import { useEffect, useRef } from 'react';
import { CanvasEngine } from '@/lib/ascii/engine';
import type { AsciiPattern } from '@/lib/ascii/types';
import { useSettings } from '@/stores/settings';
import styles from './ascii-background.module.css';
interface Props {
pattern: AsciiPattern;
}
export function AsciiBackground({ pattern }: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const engineRef = useRef<CanvasEngine | null>(null);
const backgroundOpacity = useSettings(s => s.backgroundOpacity);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const engine = new CanvasEngine(canvas);
engineRef.current = engine;
engine.start();
const observer = new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
if (width > 0 && height > 0) {
engine.resize(width, height);
}
});
observer.observe(canvas);
return () => {
observer.disconnect();
engine.stop();
};
}, []);
useEffect(() => {
engineRef.current?.setPattern(pattern);
}, [pattern]);
return <canvas className={styles.canvas} ref={canvasRef} style={{ opacity: backgroundOpacity }} />;
}