L-System Branch Growth
L 系统递归生长
A recursive grammar generates successive forked branches, so the growing figure repeats its structure at multiple scales.
Where to use it
Illustrate a branching process or add an organic animated accent to an ecology or research page. Reveal the main branches before the smaller ones so repeated rules are easier to recognize at different scales.
Practical example
An ecology lesson lets students play a model of how a branching plant grows. The stem appears first, then smaller forks repeat the same structure so students can see how one rule produces the full pattern.
AI prompt
Create branch growth in [canvas] using a small L-system. Expand production rules to a fixed depth, interpret them with a turtle and a stack for branches, then frame the paths with a bounding box. Reveal segments in traversal order, sharing a crisp static view with reduced motion.
Example code
Save the standalone HTML as a file and open it in your browser. It uses the same code as the preview.
View HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>L-System Branch Growth</title>
<style>
:root {
color-scheme: dark;
--demo-bg: #171629;
--demo-ink: #f8f5ff;
--demo-accent: #b9a6ff;
--demo-muted: #bfbbd3;
font-family: system-ui, sans-serif;
color: var(--demo-ink);
background: var(--demo-bg);
}
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; min-width: 0; }
button, input { font: inherit; }
.demo {
display: grid;
place-items: center;
align-content: center;
min-height: 100vh;
padding: 14px;
overflow: hidden;
background: radial-gradient(ellipse at 50% 24%, #28233f, var(--demo-bg) 78%);
}
.demo-button {
border: 1px solid #ffffff3d;
border-radius: 7px;
background: #ffffff12;
color: var(--demo-ink);
padding: 6px 11px;
font-size: 12px;
cursor: pointer;
}
:focus-visible {
outline: 2px solid var(--demo-accent);
outline-offset: 3px;
}
.specimen {
display: grid;
width: min(100%, 356px);
gap: 8px;
margin: 0;
justify-items: center;
}
.specimen canvas {
display: block;
width: 100%;
aspect-ratio: 2;
max-height: max(72px, calc(100vh - 65px));
border-radius: 11px;
background: linear-gradient(145deg, #232943, #14172c);
box-shadow: 0 8px 22px #090a16a8;
}
.specimen label {
display: grid;
width: 100%;
min-height: 25px;
grid-template-columns: minmax(0, auto) minmax(56px, 1fr);
align-items: center;
gap: 8px;
color: var(--demo-ink);
font-size: 12px;
}
.specimen input {
width: 100%;
margin: 0;
accent-color: #b9a6ff;
}
@media (prefers-reduced-motion: reduce) {
.specimen [data-loop-toggle] { display: none; }
}
</style>
</head>
<body>
<main class="demo">
<figure class="specimen">
<canvas role="img" aria-label="L-System Branch Growth" width="288" height="144">L-System Branch Growth</canvas>
<button class="demo-button" type="button" data-loop-toggle data-testid="effect-demo-loop-toggle">Play demo</button>
</figure>
</main>
<script>
(() => {
const canvas = document.querySelector('.specimen canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
document.querySelector('.specimen :is(input, button)').disabled = true;
return;
}
const width = 288;
const height = 144;
const turn = Math.PI * 2;
let elapsed = 0;
let variation = 0;
function dot(x, y, radius, ink) {
ctx.fillStyle = ink;
ctx.beginPath();
ctx.arc(x, y, radius, 0, turn);
ctx.fill();
}
function mix(a, b, amount) {
return a + (b - a) * amount;
}
let program = 'F';
for (let generation = 0; generation < 4; generation++) {
program = program.replaceAll('F', 'F[+F]F[-F][F]');
}
const segments = [];
const stack = [];
let pen = { x: 0, y: 0, angle: -Math.PI / 2, depth: 0 };
for (const symbol of program) {
if (symbol === '[') {
stack.push({ ...pen });
pen.depth++;
} else if (symbol === ']') pen = stack.pop();
else if (symbol === '+') pen.angle += .43;
else if (symbol === '-') pen.angle -= .59;
else if (symbol === 'F') {
const length = 5.3 * Math.pow(.88, pen.depth);
const x = pen.x + Math.cos(pen.angle) * length;
const y = pen.y + Math.sin(pen.angle) * length;
segments.push({ x: pen.x, y: pen.y, endX: x, endY: y, depth: pen.depth });
pen.x = x;
pen.y = y;
}
}
const furthest = Math.max(...segments.map((segment) => Math.abs(segment.endX)));
const highest = -Math.min(...segments.map((segment) => segment.endY));
const scale = Math.min(96 / furthest, 109 / highest);
function draw(time) {
ctx.fillStyle = '#142a2b';
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = '#7dad958f';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(42, 126);
ctx.lineTo(246, 126);
ctx.stroke();
ctx.translate(144, 125);
ctx.scale(scale, scale);
ctx.lineCap = 'round';
const order = .42 + .58 * (.5 + .5 * Math.cos(time * .63));
for (let index = 0; index < Math.ceil(segments.length * order); index++) {
const { x, y, endX, endY, depth } = segments[index];
ctx.strokeStyle = depth > 3 ? '#e2d69c' : depth > 1 ? '#9fdaa3' : '#69bd9c';
ctx.lineWidth = 1.7 / (1 + depth * .23);
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(endX, endY);
ctx.stroke();
}
}
function render() {
const ratio = Math.min(devicePixelRatio || 1, 2);
const pixelsWide = Math.max(1, Math.round(canvas.clientWidth * ratio));
const pixelsTall = Math.max(1, Math.round(canvas.clientHeight * ratio));
if (canvas.width !== pixelsWide || canvas.height !== pixelsTall) {
canvas.width = pixelsWide;
canvas.height = pixelsTall;
}
ctx.setTransform(pixelsWide / width, 0, 0, pixelsTall / height, 0, 0);
ctx.clearRect(0, 0, width, height);
ctx.save();
draw(elapsed, variation);
ctx.restore();
}
render();
new ResizeObserver(render).observe(canvas);
const button = document.querySelector('[data-loop-toggle]');
const preference = matchMedia('(prefers-reduced-motion: reduce)');
let playing = false;
let intersecting = false;
let pendingFrame = null;
let previousTime = 0;
function canAnimate() {
return playing && intersecting && !preference.matches && !document.hidden;
}
function tick(now) {
pendingFrame = null;
if (!canAnimate()) return;
elapsed += Math.min(Math.max(0, now - previousTime), 45) / 1000;
previousTime = now;
render();
pendingFrame = requestAnimationFrame(tick);
}
function syncPlayback() {
if (pendingFrame !== null) cancelAnimationFrame(pendingFrame);
pendingFrame = null;
if (canAnimate()) {
previousTime = performance.now();
pendingFrame = requestAnimationFrame(tick);
}
}
button.addEventListener('click', () => {
playing = !playing;
button.textContent = playing ? "Pause demo" : "Play demo";
button.closest('.specimen').toggleAttribute('data-playing', playing);
syncPlayback();
});
new IntersectionObserver(([entry]) => {
intersecting = entry.isIntersecting;
syncPlayback();
}).observe(canvas);
preference.addEventListener('change', syncPlayback);
document.addEventListener('visibilitychange', syncPlayback);
})();
</script>
</body>
</html>Original example by UI Skills