fractals/koch/sketch.js

45 lines
712 B
JavaScript
Raw Normal View History

2019-01-22 17:24:41 +00:00
let v1, v2;
function setup() {
createCanvas(800, 300);
v1 = createVector(50, 250);
v2 = createVector(750, 250);
background(0);
stroke(255);
koch(v1, v2, 6);
}
function koch(p1, p2, i) {
if (i === 1) connect(p1, p2);
else {
const {a, b, c, d, e} = generateEdges(p1, p2)
koch(a, b, i-1)
koch(b, c, i-1)
koch(c, d, i-1)
koch(d, e, i-1)
}
}
function connect(p1, p2) {
line(p1.x, p1.y, p2.x, p2.y);
}
function generateEdges(p1, p2) {
let v = p5.Vector.sub(p2, p1);
v.div(3);
let a = p1.copy();
let b = p5.Vector.add(p1, v);
let d = p5.Vector.sub(p2, v);
v.rotate(-PI/3);
let c = p5.Vector.add(b, v);
e = p2.copy();
return {a, b, c, d, e}
}