D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
tmcw
Full window
Github gist
Square Waves via Fourier Series
via
,
via
<!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>