L-System分形树动画需三步:定义规则并迭代生成字符串、解析字符串为绘图指令(F前进、±转向、[]压栈弹栈)、用requestAnimationFrame逐帧绘制生长过程。

要用 HTML5 Canvas 绘制基于 L-System 的动态分形树生长动画,核心是三步:定义 L-System 规则并迭代生成字符串、将字符串解析为绘图指令(如前进、转向、压栈/弹栈)、用 requestAnimationFrame 逐帧绘制“生长”过程(非一次性画完,而是逐步展开分支)。
1. 构建基础 L-System 模型(含角度、规则、初始公理)
L-System 是一种重写系统,用字符串表示树的结构。常见树规则如:
-
公理(Axiom):
F(代表向前画一段) -
规则:
F → F+[+F-F]-[-F+F](F 替换为带分支和转向的序列) -
符号含义:
-
F:向前移动并画线 -
+:左转(如 25°) -
-:右转(如 25°) -
[:保存当前坐标与角度(压栈) -
]:恢复上一次保存的状态(弹栈)
-
用 JavaScript 实现迭代生成:
function generateLSystem(axiom, rules, iterations) {
let current = axiom;
for (let i = 0; i < iterations; i++) {
let next = '';
for (let j = 0; j < current.length; j++) {
const char = current[j];
next += rules[char] || char; // 若无规则,保留原字符
}
current = next;
}
return current;
}
// 示例调用:generateLSystem('F', {'F': 'F+[+F-F]-[-F+F]'}, 4)
2. 用 Canvas 渲染字符串,支持“渐进式”生长
关键不是一次性画完所有分支,而是按字符串索引逐步执行——每帧只处理前 N 个字符,N 随时间递增,模拟“生长”感。
立即学习“前端免费学习笔记(深入)”;
- 维护一个
stack = []存储 [x, y, angle],用于[和] - 维护
currentX, currentY, currentAngle表示画笔当前位置与朝向 - 设定步长
len(随深度衰减可增强真实感,如len *= 0.85) - 每帧只解析字符串的前
progress个字符,progress从 0 线性增至字符串总长
function drawLSystem(ctx, instructions, progress, startX, startY, startAngle, len, angleDeg) {
const stack = [];
let x = startX, y = startY, a = startAngle * Math.PI / 180;
<p>ctx.beginPath();
ctx.moveTo(x, y);</p><p>for (let i = 0; i < Math.min(progress, instructions.length); i++) {
const c = instructions[i];</p><pre class='brush:php;toolbar:false;'>if (c === 'F') {
const nx = x + Math.cos(a) * len;
const ny = y + Math.sin(a) * len;
ctx.lineTo(nx, ny);
x = nx; y = ny;
} else if (c === '+') {
a += angleDeg * Math.PI / 180;
} else if (c === '-') {
a -= angleDeg * Math.PI / 180;
} else if (c === '[') {
stack.push({x, y, a});
} else if (c === ']') {
const state = stack.pop();
if (state) ({x, y, a} = state);
}} ctx.stroke(); }
3. 用 requestAnimationFrame 实现平滑生长动画
避免用 setTimeout 或固定帧率循环,优先使用 requestAnimationFrame 保证流畅,并控制生长节奏:
- 预生成完整 L-System 字符串(避免每帧重复计算)
- 设置目标总帧数(如 600 帧),每帧增加
progress += totalLength / 600 - 清空画布时用
ctx.clearRect(0, 0, canvas.width, canvas.height),但注意保留背景色或添加抗锯齿优化 - 可加入缩放/居中逻辑:将树绘制在画布中心,初始长度设为
canvas.height * 0.2
动画主循环示例:
let progress = 0;
const totalSteps = 600;
const fullInstructions = generateLSystem('F', rules, 5);
const startTime = performance.now();
<p>function animate(timestamp) {
const elapsed = timestamp - startTime;
progress = Math.min(fullInstructions.length,
(elapsed / 3000) * fullInstructions.length // 3秒长生长动画
);</p><p>ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = '#2d5a27';
ctx.lineWidth = 1.2;
drawLSystem(ctx, fullInstructions, progress,
canvas.width/2, canvas.height*0.9, -90, 8, 25);</p><p>if (progress < fullInstructions.length) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);</p>4. 增强视觉效果的小技巧
让分形树更生动,不单靠算法,也靠渲染细节:
-
线宽渐变:越深的分支(栈深度越大)线宽越细,可在解析时记录深度,或用
ctx.lineWidth = Math.max(0.5, 2 - depth * 0.3) -
颜色过渡:主干用深褐(
#5D4037),新枝用嫩绿(#81C784),按 progress 归一化插值 -
抗锯齿开启:
ctx.lineCap = 'round'; ctx.lineJoin = 'round'让转折更自然 - 轻微随机扰动:对每次转向加 ±2° 随机偏移,避免机械感(仅在 'F' 移动后微调 a)



















