Visualizing the Fourier Series of a Sawtooth Wave


Below is the sawtooth wave visualization coded in javascript.




Here is the source code for you to copy and modify


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 = 5, 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=1; i<=k; i++ )
33           {
34               radius = 60 * ( 2 / (i * Math.PI )) * Math.pow(-1, i)
35   
36               x = radius * Math.cos( i * angle )
37               y = radius * Math.sin( i * angle )
38   
39               plane.beginPath()
40               plane.arc( cx, cy, radius<0?(radius*-1):radius, 0, Math.PI * 2 )
41               plane.strokeStyle = "grey"
42               plane.stroke()
43   
44               plane.beginPath()
45               plane.moveTo(cx, cy)
46               plane.lineTo(cx+x, cy+y)
47               plane.stroke()
48   
49               cx += x
50               cy += y
51           }
52           wave.unshift(cy)
53   
54           plane.beginPath()
55           plane.moveTo(cx, cy)
56           plane.lineTo(250, cy)
57           plane.stroke()
58   
59           for( let i=0; i<wave.length; i++ )
60           {
61               plane.fillStyle = "black"
62               plane.fillRect(250+i, wave[i], 2, 2)
63           }
64           if( wave.length > 320 ) wave.pop()
65   
66           angle -= 0.03
67       }
68   
69       function clear()
70       {
71           plane.fillStyle = "white"
72           plane.strokeStyle = "black"
73           plane.fillRect(0,0, board.width, board.height)
74           plane.strokeRect(0,0,board.width, board.height )
75       }
76   </script>
77   </body>
78   </html>

To change the number of epicycles or the rotating circles, just change the value of k.



Engr. Jumar Hamac
Web Developer

Electronics Engineer by Profession.
Loves coding and painting.