The concept
An L-system (Lindenmayer, 1968) is a formal grammar: an axiom (initial string) and rewriting rules. After N iterations, the resulting string is interpreted graphically: F = move forward, + = turn left, - = turn right, [ = save, ] = restore. This produces realistic plant forms.
The code
// L-system tree
let sentence = 'F', rules = {'F':'FF+[+F-F-F]-[-F+F+F]'};
function setup() {
createCanvas(400, 280); background(11,15,20);
for (let i = 0; i < 4; i++) {
let next = '';
for (let c of sentence) next += rules[c] || c;
sentence = next;
}
translate(width/2, height); stroke(55,227,195); strokeWeight(1);
for (let c of sentence) {
if (c==='F') { line(0,0,0,-4); translate(0,-4); }
else if (c==='+') rotate(radians(22));
else if (c==='-') rotate(radians(-22));
else if (c==='[') push();
else if (c===']') pop();
}
noLoop();
}Going further
Explore other free courses on the Learn page, or book a call to discuss your project.
Want to go further?
Book a discovery call →