-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWaves.tsx
101 lines (82 loc) · 2.34 KB
/
Waves.tsx
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
'use client';
import React, { useEffect, useRef } from 'react';
interface Wave {
color: string;
speed?: number;
amplitude?: number;
height: number; // New property: height of the wave
}
interface OverlappingWavesProps {
height: number;
width: number;
waves: Wave[];
baseSpeed?: number;
baseAmplitude?: number;
}
const Waves: React.FC<OverlappingWavesProps> = ({
height,
width,
waves,
baseSpeed = 0.5,
baseAmplitude = 20,
}) => {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
let animationFrameId: number;
let startTime: number | null = null;
const setCanvasSize = () => {
if (canvas) {
canvas.width = width;
canvas.height = height;
}
};
const drawWaves = (timestamp: number) => {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
waves.forEach((wave, index) => {
ctx.beginPath();
ctx.moveTo(0, height);
const waveSpeed = wave.speed || baseSpeed;
const waveAmplitude = wave.amplitude || baseAmplitude;
const waveHeight = wave.height;
for (let x = 0; x < width; x++) {
const frequency = 0.01 + index * 0.005;
const y = Math.sin(x * frequency + elapsed * waveSpeed * 0.002 + (index * Math.PI * 2) / waves.length) * waveAmplitude;
ctx.lineTo(x, waveHeight + y);
}
ctx.lineTo(width, height);
ctx.lineTo(0, height);
ctx.fillStyle = wave.color;
ctx.globalAlpha = 0.5; // Set transparency
ctx.fill();
ctx.globalAlpha = 1; // Reset transparency
});
animationFrameId = requestAnimationFrame(drawWaves);
};
setCanvasSize();
animationFrameId = requestAnimationFrame(drawWaves);
return () => {
cancelAnimationFrame(animationFrameId);
};
}, [height, width, waves, baseSpeed, baseAmplitude]);
return (
<div
style={{ height }}
className="rounded-xl overflow-hidden"
>
<canvas
ref={canvasRef}
width={width}
height={height}
/>
</div>
);
};
export default Waves;