Sierpinski Accident

September 12th, 2008

If your anything like me, you spend your friday nights playing with random code snippets until something interesting appears - or until you pass out. Tonight I was messing with BitmapData in flash and I accidentally stumbled on a weird way to make a Sierpinski Triangle. Try running this on your flash timeline, move your mouse around:

Actionscript:
  1. stage.frameRate = 31;
  2. var canvas:BitmapData = new BitmapData(500,500, true, 0xFF000000);
  3. addChild(new Bitmap(canvas));
  4. var m:Matrix = new Matrix();
  5. m.tx = -1;
  6. addEventListener(Event.ENTER_FRAME, onLoop);
  7. function onLoop(evt:Event):void {
  8.        canvas.setPixel(mouseX, mouseY,0xFFFFFF);
  9.        canvas.copyPixels(canvas, canvas.rect, new Point(1,-1), null, null, true);
  10.        canvas.draw(canvas,m, null, BlendMode.DIFFERENCE);
  11. }

if you run that code, this is what you'll get:

Click the image above to see the flash version.

If you want a triangle that isn't skewed you can just change the matrix tx property and the copyPixels point argument:

Actionscript:
  1. stage.frameRate = 31;
  2. var canvas:BitmapData = new BitmapData(500,500, true, 0xFF000000);
  3. addChild(new Bitmap(canvas));
  4. var m:Matrix = new Matrix();
  5. m.tx = -2;
  6. addEventListener(Event.ENTER_FRAME, onLoop);
  7. function onLoop(evt:Event):void {
  8.        canvas.setPixel(mouseX, mouseY,0xFFFFFF);
  9.        canvas.copyPixels(canvas, canvas.rect, new Point(1,2), null, null, true);
  10.        canvas.draw(canvas,m, null, BlendMode.DIFFERENCE);
  11. }

Leave a Reply