Public
Edited
Aug 30, 2023
Fork of Koch Fractal
1 star
Insert cell
Insert cell
Insert cell
{
const w = width,
h = width,
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 = [];
let m = 150;
let ww = width - m - m;
let uu = ww / 4;
lines.push(new KochLine(context, [m + uu * 2, m], [m + uu, m]));
lines.push(new KochLine(context, [m + uu * 3, m + uu], [m + uu * 2, m]));
lines.push(
new KochLine(context, [m + uu * 3, m + uu * 2], [m + uu * 3, m + uu])
);
lines.push(
new KochLine(context, [m + uu * 2, m + uu * 3], [m + uu * 3, m + uu * 2])
);

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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more