Last active
December 20, 2015 15:18
-
-
Save tmcw/6152754 to your computer and use it in GitHub Desktop.
Square Waves via Fourier Series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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