Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created August 5, 2013 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/6152764 to your computer and use it in GitHub Desktop.
Save tmcw/6152764 to your computer and use it in GitHub Desktop.
Square Wave Via Fourier Transform
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>fourier square wave</title>
<style>body { margin:0; padding:0; }</style>
</head>
<body>
<script>
var c = document.body.appendChild(document.createElement('canvas'));
var w = 950, h = 500;
c.width = w;
c.height = h;
var ctx = c.getContext('2d');
ctx.fillStyle = '#fff';
ctx.strokeStyle = '#000';
function wave(t, n, f) {
var val = 0;
for (var k = 1; k < n; k ++) {
val += Math.sin(Math.PI * 2 * ((2 * k) - 1) * f * t) / ((2 * k) - 1);
}
return (2 / Math.PI) * val;
}
function draw(n, f, a) {
ctx.fillRect(0,0,w,h);
ctx.beginPath();
ctx.moveTo(0,h/2);
ctx.lineTo(w,h/2);
ctx.strokeStyle = '#aaf';
ctx.stroke();
ctx.strokeStyle = '#000';
ctx.beginPath();
for (var t = 0; t < Math.PI * 4; t += 0.01) {
var y = wave(t, n, f)
ctx.lineTo(t * 100, (y * 100) + h/2);
}
ctx.stroke();
}
document.onmousemove = function(e) {
draw((Math.floor(e.pageX / 20)) + 1, 0.2);
}
var it = 0, interval = window.setInterval(function() {
if (++it < 20) draw(it + 1, 0.2);
else window.clearInterval(it);
}, 100);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment