AudioForge / frontend /src /components /sound-wave-background.tsx
OnyxlMunkey's picture
c618549
"use client";
import { useEffect, useRef } from "react";
export function SoundWaveBackground() {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
// Set canvas size
const resizeCanvas = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
resizeCanvas();
window.addEventListener("resize", resizeCanvas);
// Animation variables
let animationFrameId: number;
let time = 0;
// Wave configuration
const waves = [
{ amplitude: 30, frequency: 0.02, speed: 0.01, color: "rgba(139, 92, 246, 0.1)" },
{ amplitude: 40, frequency: 0.015, speed: 0.015, color: "rgba(168, 85, 247, 0.08)" },
{ amplitude: 25, frequency: 0.025, speed: 0.008, color: "rgba(192, 132, 252, 0.06)" },
];
const drawWave = (
amplitude: number,
frequency: number,
speed: number,
color: string,
offset: number
) => {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 2;
for (let x = 0; x < canvas.width; x++) {
const y =
canvas.height / 2 +
offset +
Math.sin(x * frequency + time * speed) * amplitude;
if (x === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
};
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw multiple waves with different offsets
waves.forEach((wave, index) => {
const offset = (index - 1) * 80;
drawWave(
wave.amplitude,
wave.frequency,
wave.speed,
wave.color,
offset
);
});
time += 1;
animationFrameId = requestAnimationFrame(animate);
};
animate();
return () => {
window.removeEventListener("resize", resizeCanvas);
cancelAnimationFrame(animationFrameId);
};
}, []);
return (
<canvas
ref={canvasRef}
className="fixed inset-0 pointer-events-none z-0"
aria-hidden="true"
/>
);
}