Published
Edited
Nov 7, 2019
2 forks
1 star
Insert cell
Insert cell
Insert cell
{
const w = width,
h = 300,
context = DOM.context2d(w,h);
const lines = generateKochFractal(context, levels);
for(let line of lines){
line.show();
}
return context.canvas;
}
Insert cell
function generateKochFractal(context, levels){
let lines = [];
const start = [0,0],
end = [context.canvas.width,0];
lines.push(new KochLine(context, start, end));
for(let i = 0; i < levels; i++){
let next_lines = [];
for (let line of lines){

const a = line.kochA(),
b = line.kochB(),
c = line.kochC(),
d = line.kochD(),
e = line.kochE();

next_lines.push(new KochLine(context, a, b));
next_lines.push(new KochLine(context, b, c));
next_lines.push(new KochLine(context, c, d));
next_lines.push(new KochLine(context, d, e));
}
lines = next_lines;
}

return lines;
}
Insert cell
class KochLine{
constructor(context, start, end){
this.context = context;
this.start = start;
this.end = end;
}
show(){
this.context.beginPath();
this.context.moveTo(this.start[0], this.start[1]);
this.context.lineTo(this.end[0], this.end[1]);
this.context.stroke();
}
kochA(){
return this.start;
}
kochB(){
let v = [this.end[0] - this.start[0], this.end[1] - this.start[1]];
v = v.map(d => d/3);
return this.start.map((d,i) => d + v[i]);
}
kochC(){
let v = [this.end[0] - this.start[0], this.end[1] - this.start[1]];
v = v.map(d => d/3);
const rotated = this.rotate(v, Math.PI/3);
return this.start.map((d,i) => d + v[i] + rotated[i]);
}
kochD(){
let v = [this.end[0] - this.start[0], this.end[1] - this.start[1]];
v = v.map(d => d/3);
return this.start.map((d,i) => d + 2 * v[i]);
}
kochE(){
return this.end;
}
rotate(vector, angle){
const cos = Math.cos(angle),
sin = Math.sin(angle);
return [vector[0]*cos - vector[1]*sin, vector[0]*sin + vector[1]*cos];
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more