fractals/sierpinski/sketch.js

34 lines
668 B
JavaScript
Raw Permalink Normal View History

2019-01-22 16:38:35 +00:00
let v1, v2, v3;
function setup() {
createCanvas(500, 450);
v1 = createVector(250, 50);
v2 = createVector(50, 396);
v3 = createVector(450, 396);
background(0);
stroke(255);
sierpinski(v1, v2, v3, 8);
}
function sierpinski(p1, p2, p3, i) {
if (i === 1) tri(p1, p2, p3)
else {
let m1 = half(p2, p3);
let m2 = half(p3, p1);
let m3 = half(p1, p2)
sierpinski(p1, m3, m2, i-1);
sierpinski(p2, m3, m1, i-1);
sierpinski(p3, m1, m2, i-1);
}
}
function tri(p1, p2, p3) {
line(p1.x, p1.y, p2.x, p2.y);
line(p1.x, p1.y, p3.x, p3.y);
line(p3.x, p3.y, p2.x, p2.y);
}
function half(p1, p2) {
return p1.copy().add(p2).div(2);
}