- Add links to JSFiddle
- Visualize with bl.ocks.org.
- Vistualize with GistRun.
I am revisiting the Fourier transform so I thought it might be nice to come up with some visualizations. My first stop was to plot a sine wave in JavaScript, then to animate it. I am using the window.requestAnimationFrame()
method. I've documented the steps in reverse order.
The end result is an oscillating sine wave. Nothing ground-breaking but it looks pretty cool to me.
The JavaScript function to plot the sine wave uses the Math.sin()
function, which is called repeatedly given a different starting point on the y-axis. See the simple plot below. In this case, the draw()
function makes the repeat calls via window.requestAnimationFrame(draw)
.
function draw() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.clearRect(0, 0, 500, 500);
showAxes(context);
context.save();
plotSine(context, step, 50);
context.restore();
step += 4;
window.requestAnimationFrame(draw);
}
Note: The astute observer may observe the animation above isn't actually JavaScript but is instead an animated gif. I did this since it is currently not possible to run JavaScript from a gist although it is possible using bl.ocks.org
.
After I learned to plot a sine wave, I visualized how to draw multiple sine waves in order to achieve the oscillation effect in the animation. It looked pretty cool, so I kept it around. It reminds me of Spirograph. 😄
The step
advances the starting point along the y-axis.
var step = 4;
for (var i = -4; i < canvas.height; i += step) {
plotSine(context, i, 54 + i);
}
My initial attempt to draw a sine wave on an HTML5
canvas.
<body onload="init()">
<h3>Oscillating Sine Wave</h3>
<canvas id="canvas" width="500" height="100"></canvas>
</body>
function plotSine(ctx) {
var width = ctx.canvas.width;
var height = ctx.canvas.height;
var scale = 20;
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "rgb(66,44,255)";
var x = 0;
var y = 0;
var amplitude = 40;
var frequency = 20;
//ctx.moveTo(x, y);
while (x < width) {
y = height/2 + amplitude * Math.sin(x/frequency);
ctx.lineTo(x, y);
x = x + 1;
}
ctx.stroke();
}
Interesting tidbit: If we uncomment ctx.moveTo(x, y)
just before the loop we get a vertical line.
I found this animated gif in Reddit.
See This should be the first thing shown in any Trigonometry class.
From the Fourier series definition in Wikipedia.