xxxxxxxxxx
67
class LineSeg {
constructor(x1, y1, x2, y2) {
this.p1 = createVector(x1, y1);
this.p2 = createVector(x2, y2);
}
show() {
line(this.p1.x, this.p1.y, this.p2.x, this.p2.y);
}
}
class Curve {
constructor(points,segRate) {
this.points = [];
this.lines = [];
for (let i = 0; i < points.length; i++) {
this.points.push(points[i]);
}
this.makeCurve();
this.subdiv(8,segRate);
}
makeCurve() {
for (let i = 0; i < this.points.length-1; i++) {
let start = this.points[i];
let end = this.points[i + 1];
this.lines.push(new LineSeg(start.x, start.y, end.x, end.y))
}
}
subdiv(n, segRate) {
while (n > 0) {
this.chopLines(segRate);
let newCurve = [];
for (let i = 0; i < this.lines.length - 1; i++) {
newCurve.push(this.lines[i]);
let start = this.lines[i].p2;
let end = this.lines[i + 1].p1;
newCurve.push(new LineSeg(start.x, start.y, end.x, end.y));
}
newCurve.push(this.lines.pop());
this.lines = newCurve;
n--;
}
}
chopLines(segRate) {
for (let i = 0; i < this.lines.length; i++) {
let x1 = this.lines[i].p1.x + segRate * (this.lines[i].p2.x - this.lines[i].p1.x);
let y1 = this.lines[i].p1.y + segRate * (this.lines[i].p2.y - this.lines[i].p1.y);
let x2 = this.lines[i].p1.x + (1 - segRate) * (this.lines[i].p2.x - this.lines[i].p1.x);
let y2 = this.lines[i].p1.y + (1 - segRate) * (this.lines[i].p2.y - this.lines[i].p1.y);
let newLine = new LineSeg(x1, y1, x2, y2);
this.lines[i] = newLine;
}
}
show() {
for (let i = 0; i < this.lines.length; i++) {
this.lines[i].show();
}
}
}