Sierpinski Triangle in AS3

Today we will take a look at recursive fractal drawing in ActionScript 3. We will draw a Sierpinski Triangle.

Sierpinski triangle

Sierpinski triangle is a fractal image, which we can construct by following these steps:
  1. Draw a black triangle
  2. Remove the "inner triangle" and call this function on 3 smaller triangles, which were created around
You can read more on Wikipedia page.

The code in ActionScript 3

var limit:int = 6;

function drawTriangle(x:Number, y:Number, level:int, size:Number):void
{
   if(level==0)  // we draw a black triangle on 0. level
      with(graphics)
      {
         clear();
         beginFill(0x00);
         moveTo(x, y-size);
         lineTo( x + size * 1.73/2, y + size/2);
         lineTo( x - size * 1.73/2, y + size/2);
         moveTo(x, y-size);
         endFill();
      }
   if(level == limit) return; // if we reached the limit of recursion, we return
   with(graphics)    // drawing a white triangle
   {
      beginFill(0xffffff);
      moveTo(x, y+size/2);
      lineTo( x - size * 1.73/4, y - size/4);
      lineTo( x + size * 1.73/4, y - size/4);
      moveTo(x, y+size/2);
      endFill();
   }
   // drawing triangles around
   drawTriangle(x, y - size/2, level+1, size/2); // tr. at top
   drawTriangle(x - size * 1.73/4, y + size/4, level+1, size/2); // bottom right
   drawTriangle(x + size * 1.73/4, y + size/4, level+1, size/2); // bottom left
}

Old comments (closed because of spam)

One Comment

  1. Marius Žilėnas said:

    Hi,
    this is my implementation of Sierpinski triangle. Thought it might be interesting to share implementation in JavaScript.

    http://jsfiddle.net/mzilenas/653Je/6/embedded/result/

    November 21st, 2013