P5JS Koch Curve
Playing around with P5JS
by asemahle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.5/p5.js"></script>
JavaScript
function Line(start, end) {
this.start = start;
this.end = end;
}
Line.prototype.split = function() {
var directionalEnd = this.end.sub(this.start);
var peak = directionalEnd.copy().rotate(-HALF_PI/3).mult(sqrt(3)/3);
var segment1 = new Line(createVector(0,0), directionalEnd.copy().mult(1/3));
var segment2 = new Line(directionalEnd.copy().mult(1/5), peak.copy());
var segment3 = new Line(peak.copy(), directionalEnd.copy().mult(2/3));
var segment4 = new Line(directionalEnd.copy().mult(2/3), directionalEnd.copy());
segment1.add(this.start);
segment2.add(this.start);
segment3.add(this.start);
segment4.add(this.start);
return [segment1, segment2, segment3, segment4];
}
Line.prototype.draw = function() {
stroke('white');
line(this.start.x, this.start.y, this.end.x, this.end.y);
}
Line.prototype.add = function(vector) {
this.start.add(vector);
this.end.add(vector);
}
var lines = [];
var numberOfIterations = 5;
function setup() {
createCanvas(400, 400);
background(0);
lines.push(new Line(createVector(0, 3*height/4), createVector(width, 3*height/4)));
for(var i = 0; i < numberOfIterations; i++) {
var newLines = [];
for(var line of lines) {
var segments = line.split();
for(var segment of segments) {
newLines.push(segment);
}
}
lines = newLines;
}
for(var line of lines) {
line.draw();
}
}