The more Fourier coefficients we add, the better the approximation becomes.
A Pen by Johan Karlsson on CodePen.
<button onclick="start()" class="float">Re-start</button> | |
<div class="title"> | |
Square Wave Approximation With Fourier Series | |
</div> | |
<canvas id="canvas"></canvas> |
/* | |
http://en.wikipedia.org/wiki/Square_wave | |
*/ | |
var canvas = document.getElementById("canvas"); | |
var ctx = canvas.getContext("2d"); | |
var π = Math.PI; | |
var f = 1; | |
var t; | |
var numberOfIterations; | |
var tick = 1; | |
var y; | |
function calcY(t) { | |
var localY = 0; | |
for(var k = 1; k <= numberOfIterations; k+=2) { | |
localY += 4/(π*k) * Math.sin(2*π*k*f*t); | |
} | |
localY = localY * canvas.height/2*0.75 + canvas.height/2; | |
return localY; | |
} | |
function draw() { | |
requestAnimationFrame(draw); | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
ctx.beginPath(); | |
numberOfIterations = 1 + Math.round(tick * tick * tick * 0.0000002); | |
for(var x = 0; x <= canvas.width; x++) { | |
t = x/canvas.width; | |
y = calcY(t); | |
ctx.lineTo(x*0.8+canvas.width*0.1, y); | |
} | |
ctx.stroke(); | |
ctx.fillText("k = " + numberOfIterations, 10, 150); | |
tick++; | |
} | |
function start() { | |
canvas.width = window.innerWidth; | |
canvas.height = window.innerHeight; | |
tick = 1; | |
ctx.font = "48px serif"; | |
draw(); | |
} | |
start(); |
The more Fourier coefficients we add, the better the approximation becomes.
A Pen by Johan Karlsson on CodePen.
body { | |
margin: 0; | |
overflow: hidden; | |
} | |
.title { | |
position:absolute; | |
left: 50%; | |
top: 50%; | |
transform: translate(-50%, -50%); | |
font-size: xx-large; | |
text-align: center; | |
} | |
.float { | |
position: absolute; | |
margin: 2vmin; | |
} |