/**
* Taylor series
* by Kazuki Maeda
* Last-Modified: May 12, 2017
*/
var canvasWidth = 1000, canvasHeight = 200;
var canvasMargin = 1;
var canvas;
var canvasMin = -20, canvasMax = 20;
var wave;
window.onload = function(){
init();
}
function init(){
// canvas
canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
canvas.setAttribute('width', canvasWidth+canvasMargin*2);
canvas.setAttribute('height', canvasHeight+canvasMargin*2);
document.getElementById('canvas').removeChild(document.getElementById('canvas').firstChild);
document.getElementById('canvas').appendChild(canvas);
var box = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
box.setAttribute('width', ''+canvasWidth);
box.setAttribute('height', canvasHeight);
box.setAttribute('x', canvasMargin);
box.setAttribute('y', canvasMargin);
box.setAttribute('stroke', 'white');
canvas.appendChild(box);
var midline = document.createElementNS('http://www.w3.org/2000/svg', 'line');
midline.setAttribute('x1', canvasMargin);
midline.setAttribute('y1', canvasMargin+canvasHeight/2);
midline.setAttribute('x2', canvasMargin+canvasWidth);
midline.setAttribute('y2', canvasMargin+canvasHeight/2);
midline.setAttribute('stroke', 'white');
canvas.appendChild(midline);
var midline2 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
midline2.setAttribute('x1', canvasMargin+canvasWidth/2);
midline2.setAttribute('y1', canvasMargin);
midline2.setAttribute('x2', canvasMargin+canvasWidth/2);
midline2.setAttribute('y2', canvasMargin+canvasHeight);
midline2.setAttribute('stroke', 'white');
canvas.appendChild(midline2);
wave = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
wave.setAttribute('stroke', '#7FFF00');
wave.setAttribute('stroke-width', '3');
wave.setAttribute('fill', 'none');
canvas.appendChild(wave);
document.getElementById('N').addEventListener('keypress', updateNK);
document.getElementById('N').addEventListener('blur', updateN);
document.getElementById('Nslider').addEventListener('change', updateNSlider);
document.getElementById('Nslider').addEventListener('input', updateNSlider);
draw();
}
function draw(){
wave.setAttribute('stroke', '#7FFF00');
var N = parseFloat(document.getElementById('N').value);
var points = '';
for(var j = 0; j <= canvasWidth; ++j){
var tmp = 0.0;
var f = 1.0;
for(var n = 0; n < N; ++n){
if(n != 0)
f *= (2*n)*(2*n+1);
tmp += Math.pow(-1.0, n)*Math.pow(canvasMin+(canvasMax-canvasMin)/canvasWidth*j, 2*n+1)/f;
}
if(Math.abs(tmp) <= 2)
points += ' ' + (canvasMargin+parseFloat(canvasWidth)*j/canvasWidth) + ',' + (canvasMargin+canvasHeight-(tmp+1.0)/2*canvasHeight);
}
wave.setAttribute('points', points);
}
function updateN(e){
document.getElementById(e.target.id + 'slider').value = parseFloat(e.target.value);
draw();
}
function updateNK(e){
if(e.keyCode == 13)
updateVol(e);
}
function updateNSlider(e){
document.getElementById(e.target.id.slice(0, -6)).value = parseFloat(e.target.value);
draw();
}