Visualizing the Square Wave Fourier Series
Here is the visualization of the Fourier Series of a Square Wave
Here is the source code
HTML
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta name="viewport" content="width=device-width, initial-scale=1.0">
5 <title>Fourier Series</title>
6 <style>
7 #plane {
8 position: absolute;
9 top: 50%;
10 left: 50%;
11 transform: translate(-50%, -50%);
12 }
13 </style>
14 </head>
15 <body>
16 <canvas id="plane" width="600" height="300"></canvas>
17
18 <script>
19 let board = document.getElementById("plane")
20 let plane = board.getContext("2d")
21 let angle = 0, k = 20, radius, wave = []
22
23 setInterval( draw, 20 )
24
25 function draw()
26 {
27 clear()
28 let x = 0
29 let y = 0
30 let cx = 120, cy = 150
31
32 for( let i=0; i<k; i++ )
33 {
34 let n = 2 * i + 1 // odd number
35 radius = 40 * ( 4 / ( n * Math.PI ) )
36
37 x = radius * Math.cos( n * angle )
38 y = radius * Math.sin( n * angle )
39
40 plane.beginPath()
41 plane.arc( cx, cy, radius, 0, Math.PI * 2 )
42 plane.strokeStyle = "grey"
43 plane.stroke()
44
45 plane.beginPath()
46 plane.moveTo(cx, cy)
47 plane.lineTo(cx+x, cy+y)
48 plane.stroke()
49
50 cx += x
51 cy += y
52 }
53 wave.unshift(cy)
54
55 plane.beginPath()
56 plane.moveTo(cx, cy)
57 plane.lineTo(250, cy)
58 plane.stroke()
59
60 for( let i=0; i<wave.length; i++ )
61 {
62 plane.fillStyle = "black"
63 plane.fillRect(250+i, wave[i], 2, 2)
64 }
65 if( wave.length > 320 ) wave.pop()
66
67 angle -= 0.03
68 }
69
70 function clear()
71 {
72 plane.fillStyle = "white"
73 plane.strokeStyle = "black"
74 plane.fillRect(0,0, board.width, board.height)
75 plane.strokeRect(0,0,board.width, board.height )
76 }
77 </script>
78 </body>
79 </html>
To change the number of epicycles or the rotating circles, just change the value of k