JavaScript · Canvas 2D

L-System 信号蕨

通过字符串重写规则生成可重复的植物分形。

L-System 信号蕨

通过字符串重写规则生成可重复的植物分形。

L-SystemCanvas

运行方式:在浏览器控制台调用 drawFern(canvas)

SOURCE / 只读源码

完整代码

export function drawFern(canvas) {
  const ctx = canvas.getContext('2d')
  let code = 'X'
  for (let i = 0; i < 6; i++) code = [...code].map(c => c === 'X' ? 'F+[[X]-X]-F[-FX]+X' : c === 'F' ? 'FF' : c).join('')
  ctx.translate(canvas.width / 2, canvas.height)
  ctx.strokeStyle = '#087d6d'
  for (const token of code) {
    if (token === 'F') { ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(0, -3); ctx.stroke(); ctx.translate(0, -3) }
    else if (token === '+') ctx.rotate(.38)
    else if (token === '-') ctx.rotate(-.38)
    else if (token === '[') ctx.save()
    else if (token === ']') ctx.restore()
  }
}