home page icon Flash Bestiary / Natural Phenomena / Fern Fractal

Fern Fractal

This program draws a fern or tree using a recursive function (a function which calls itself). Recursion is commonly used to create fractals, as it results in self-similarity.

Increasing the level of recursion will make the tree look better, but will also make it take longer to draw. At level 10 it can take a looooooong time to draw. Be patient.

The method I'm using is closely related to (and produces similar results to) an L-System or Lindenmeyer system. It's faster than an L-System, but not as general purpose, because the basic structure of the tree is hard-coded into the drawing algorithm.

The source code is surprisingly short. Here's the part which draws the tree:

function drawFern(px,py,a,rad,level)
  var cx = px+Math.cos(a)*rad*trunkRatio;
  var cy = py+Math.sin(a)*rad*trunkRatio;
  graphics.lineStyle(level*trunkThick, colors[level], 100);
  graphics.lineTo(cx, cy);
  if (level > 0) {
    a += bendAngle;

UPDATE: The source code below now contains an Actionscript 3 version, in addition to the original Flash MX code.


sourcecode iconDownload the flash project
book iconJim's Favorite Actionscript Books
wiki iconAsk Jim about Actionscript
Next: Deep Blue Sea

Having trouble opening the project? You may need to Upgrade to Flash CS3

Copyright © 2003,2008 by Jim Bumgardner. All Rights Reserved.        Leave Jim some feedback