Public
Edited
Apr 1
1 fork
Insert cell
Insert cell
{
const width = 640;
const height = 240;
const sentence = lsystem("F", 4, {
F: "FF+[+F-F-F]-[-F+F+F]"
});
const data = turtle(sentence, 4, 25);

function lsystem(sentence, count, rules) {
for (let i = 0; i < count; i++) {
let current = "";
for (let j = 0, c; j < sentence.length; j++) {
current += rules[(c = sentence.charAt(j))] ? rules[c] : c;
}
sentence = current;
}
return sentence;
}

function turtle(sentence, length, angle) {
const data = [];
const mat = cm.mat();
for (let i = 0; i < sentence.length; i++) {
const c = sentence.charAt(i);
if (c === "+") mat.rotate(angle);
else if (c === "-") mat.rotate(-angle);
else if (c === "[") mat.push();
else if (c === "]") mat.pop();
else if (c === "F") {
data.push({ d: `M0,0L0,${-length}`, transform: mat.toString() });
mat.translate(0, -length);
}
}
return data;
}

const app = cm.app({
width: width,
height: height,
draw: [
cm.svg("g", {
transform: `translate(${width / 2}, ${height})`,
stroke: "black",
children: [
cm.svg("path", data, {
d: (d) => d.d,
transform: (d) => d.transform
})
]
})
]
});

return app.render();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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