|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect, useRef } from 'react'; |
| 4 | + |
| 5 | +interface Particle { |
| 6 | + x: number; |
| 7 | + y: number; |
| 8 | + size: number; |
| 9 | + speedY: number; |
| 10 | + speedX: number; |
| 11 | + opacity: number; |
| 12 | + opacitySpeed: number; |
| 13 | +} |
| 14 | + |
| 15 | +function createParticle(width: number, height: number): Particle { |
| 16 | + return { |
| 17 | + x: Math.random() * width, |
| 18 | + y: Math.random() * height - height, |
| 19 | + size: Math.random() * 1.5 + 0.5, |
| 20 | + speedY: Math.random() * 0.4 + 0.1, |
| 21 | + speedX: (Math.random() - 0.5) * 0.2, |
| 22 | + opacity: 0, |
| 23 | + opacitySpeed: Math.random() * 0.003 + 0.001, |
| 24 | + }; |
| 25 | +} |
| 26 | + |
| 27 | +export default function ParticleCanvas() { |
| 28 | + const canvasRef = useRef<HTMLCanvasElement>(null); |
| 29 | + |
| 30 | + useEffect(() => { |
| 31 | + const canvas = canvasRef.current; |
| 32 | + if (!canvas) return; |
| 33 | + const ctx = canvas.getContext('2d'); |
| 34 | + if (!ctx) return; |
| 35 | + |
| 36 | + let animId: number; |
| 37 | + const PARTICLE_COUNT = 60; |
| 38 | + const particles: Particle[] = []; |
| 39 | + |
| 40 | + function resize() { |
| 41 | + if (!canvas) return; |
| 42 | + canvas.width = window.innerWidth; |
| 43 | + canvas.height = window.innerHeight; |
| 44 | + } |
| 45 | + |
| 46 | + resize(); |
| 47 | + window.addEventListener('resize', resize); |
| 48 | + |
| 49 | + for (let i = 0; i < PARTICLE_COUNT; i++) { |
| 50 | + const p = createParticle(canvas.width, canvas.height); |
| 51 | + p.y = Math.random() * canvas.height; // 초기엔 화면 전체에 분산 |
| 52 | + particles.push(p); |
| 53 | + } |
| 54 | + |
| 55 | + function draw() { |
| 56 | + if (!canvas || !ctx) return; |
| 57 | + |
| 58 | + ctx.clearRect(0, 0, canvas.width, canvas.height); |
| 59 | + |
| 60 | + for (const p of particles) { |
| 61 | + p.y += p.speedY; |
| 62 | + p.x += p.speedX; |
| 63 | + p.opacity = Math.min(p.opacity + p.opacitySpeed, 0.55); |
| 64 | + |
| 65 | + // 화면 밖으로 나가면 위에서 다시 |
| 66 | + if (p.y > canvas.height + 10) { |
| 67 | + const fresh = createParticle(canvas.width, canvas.height); |
| 68 | + Object.assign(p, fresh); |
| 69 | + } |
| 70 | + |
| 71 | + ctx.beginPath(); |
| 72 | + ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2); |
| 73 | + ctx.fillStyle = `rgba(220, 185, 120, ${p.opacity})`; |
| 74 | + ctx.fill(); |
| 75 | + } |
| 76 | + |
| 77 | + animId = requestAnimationFrame(draw); |
| 78 | + } |
| 79 | + |
| 80 | + draw(); |
| 81 | + |
| 82 | + return () => { |
| 83 | + cancelAnimationFrame(animId); |
| 84 | + window.removeEventListener('resize', resize); |
| 85 | + }; |
| 86 | + }, []); |
| 87 | + |
| 88 | + return ( |
| 89 | + <canvas |
| 90 | + ref={canvasRef} |
| 91 | + className="pointer-events-none fixed inset-0 z-10" |
| 92 | + /> |
| 93 | + ); |
| 94 | +} |
0 commit comments