Sierpinski Accident
September 12th, 2008If 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:
-
stage.frameRate = 31;
-
var canvas:BitmapData = new BitmapData(500,500, true, 0xFF000000);
-
addChild(new Bitmap(canvas));
-
var m:Matrix = new Matrix();
-
m.tx = -1;
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
canvas.setPixel(mouseX, mouseY,0xFFFFFF);
-
canvas.copyPixels(canvas, canvas.rect, new Point(1,-1), null, null, true);
-
canvas.draw(canvas,m, null, BlendMode.DIFFERENCE);
-
}
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:
-
stage.frameRate = 31;
-
var canvas:BitmapData = new BitmapData(500,500, true, 0xFF000000);
-
addChild(new Bitmap(canvas));
-
var m:Matrix = new Matrix();
-
m.tx = -2;
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
canvas.setPixel(mouseX, mouseY,0xFFFFFF);
-
canvas.copyPixels(canvas, canvas.rect, new Point(1,2), null, null, true);
-
canvas.draw(canvas,m, null, BlendMode.DIFFERENCE);
-
}