Drawing a Continuous Fractal Curve
/**
* Copyright husam.adil73 ( http://wonderfl.net/user/husam.adil73 )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/MKvI
*/
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
public class ch35ex4 extends Sprite {
protected var iterations:int = 0;
protected var hilbertCurve:Hilbert;
public function ch35ex4() {
hilbertCurve = new Hilbert(stage.stageWidth, stage.stageHeight);
addChild(hilbertCurve);
stage.addEventListener(MouseEvent.CLICK, onClick);
onClick(null);
}
protected function onClick(event:MouseEvent):void {
if (++iterations > 7) {
iterations = 1;
hilbertCurve.scaleX = hilbertCurve.scaleY = 1;
}
hilbertCurve.clear();
hilbertCurve.hilbert(iterations);
hilbertCurve.scaleY = hilbertCurve.scaleX /= 2;
}
}
}
import flash.display.Shape;
class Hilbert extends Shape {
protected const U:int = 0, R:int = 1, D:int = 2, L:int = 3;
protected var curx:Number, cury:Number;
protected var len:Number;
public function Hilbert(w:Number, h:Number) {
len = Math.min(h, w);
}
public function clear():void {
graphics.clear();
graphics.lineStyle(0);
cury = 0;
curx = len/2;
graphics.moveTo(curx, cury);
}
public function hilbert(iter:int, dir:int = U):void {
if (--iter < 0) return;
switch(dir) {
case L: //left-facing cup is drawn right, down, left
hilbert(iter, U);
drawSegment(R);
hilbert(iter, L);
drawSegment(D);
hilbert(iter, L);
drawSegment(L);
hilbert(iter, D);
break;
case R: //right-facing cup is drawn left, up, right
hilbert(iter, D);
drawSegment(L);
hilbert(iter, R);
drawSegment(U);
hilbert(iter, R);
drawSegment(R);
hilbert(iter, U);
break;
case U: //up-facing cup is drawn down, right, up
hilbert(iter, L);
drawSegment(D);
hilbert(iter, U);
drawSegment(R);
hilbert(iter, U);
drawSegment(U);
hilbert(iter, R);
break;
case D: //down-facing cup is drawn up, left, down
hilbert(iter, R);
drawSegment(U);
hilbert(iter, D);
drawSegment(L);
hilbert(iter, D);
drawSegment(D);
hilbert(iter, L);
break;
}
}
protected function drawSegment(dir:Number):void {
switch (dir) {
case U: graphics.lineTo(curx, cury -= len); break;
case R: graphics.lineTo(curx += len, cury); break;
case D: graphics.lineTo(curx, cury += len); break;
case L: graphics.lineTo(curx -= len, cury); break;
}
}
}