JS_Projects/fourierSeries/drawing.js

127 lines
3.5 KiB
JavaScript
Raw Normal View History

2022-11-09 23:34:49 +01:00
let res = 5;
const pi = Math.PI;
const p = 2;
class Drawing {
constructor(xoffset, yoffset, scale, num) {
this.t = 0;
this.n = num;
this.x = [0];
this.y = [0];
this.a = [0];
this.r = [0];
this.xoffset = xoffset;
this.yoffset = yoffset;
this.scale = scale;
this.poslog = [];
this.fc = 0;
this.refresh();
this.setPos();
}
refresh() {
this.t = 0;
this.x[0] = 0;
this.y[0] = 0;
for (let i = 0; i < this.n; i++) {
this.x[i + 1] = this.x[i];
this.y[i + 1] = this.y[i];
this.a[i] = 0;
this.r[i] = random(0.5, 3.5);
}
this.x = this.x.slice(0, this.n - 1);
this.y = this.y.slice(0, this.n - 1);
this.poslog = [];
this.setPos();
}
update() {
this.t += 1 / 144;
for (let i = 0; i < this.n; i++) {
let m = i * 2 + 1;
this.a[i] = sin(m * this.t);
this.r[i] = 4/(m*pi);
}this.setPos();
if (this.poslog.length >= 1) {
if (Math.abs(this.x[this.n - 1] - this.poslog[this.poslog.length - 1].x) > 5) {
this.logPos();
}
} else
this.logPos();
}
fx(x, n) {
let a = 0;
if (n % 2 == 0) {
let b = 0;
} else {
let b = (4) / (n * pi);
}
let result = 0;
let l = pi;
for (let i = 1; i <= n; i++) {
result += sin((2*i-1)*x)/(2*i-1);
}
return result;
}
show() {
this.fc++;
push();
translate(this.xoffset / 2, this.yoffset);
strokeWeight(10 * this.scale);
point(0, 0);
strokeWeight(10 * this.scale);
for (let i = 0; i < this.n; i++) {
point(this.x[i], this.y[i]);
}
strokeWeight(4 * this.scale);
line(0, 0, this.x[0], this.y[0]);
for (let i = 1; i < this.n; i++) {
line(this.x[i - 1], this.y[i - 1], this.x[i], this.y[i]);
}
pop();
this.showTrail();
}
setPos() {
this.x[0] = cos(this.a[0]*2*pi) * this.r[0] * 100 * this.scale;
this.y[0] = sin(this.a[0]*2*pi) * this.r[0] * 100 * this.scale;
for (let i = 1; i < this.n; i++) {
this.x[i] = this.x[i - 1] + cos(this.a[i]) * this.r[i] * 100 * this.scale;
this.y[i] = this.y[i - 1] + sin(this.a[i]) * this.r[i] * 100 * this.scale;
}
}
logPos() {
if (this.poslog.length < 144 / this.scale * 10) {
//this.poslog.push(createVector(this.t, this.y[this.n - 1]));
this.poslog.push(createVector(this.t, 100 * this.fx(map(this.t, 0, p*pi, -pi, pi), 101)));
} else {
this.poslog.shift();
//this.poslog.push(createVector(this.t, this.y[this.n - 1]));
this.poslog.push(createVector(this.t, 100 * this.fx(map(this.t, 0, p*pi, -pi, pi), 101)));
}
}
showTrail() {
push();
translate(this.xoffset / 2, this.yoffset);
strokeWeight(3 * this.scale);
stroke(33);
noFill();
line(this.scale * 500, this.scale * 500, this.scale * 500, -this.scale * 500);
beginShape();
for (let i = 0; i < this.poslog.length; i++) {
vertex(-this.poslog[i].x * 50 + this.t * 50 + this.scale * 500, this.poslog[i].y);
}
endShape();
pop();
}
}