Dynamic Graphics and Function.apply()

var cmds:Array = [["lineStyle", 0, 0xFF0000], ["drawCircle",100, 100, 50], ["drawRect", 50, 50, 100, 100]];
cmds.push(["drawCircle", 100, 100, 70]);
cmds.push(["beginFill",  0x555555]);
cmds.push(["drawRoundRect", 80, 80, 40, 40, 10, 10]);
cmds.push(["endFill"]);

render(cmds);

function render(p:Array):void {
	for (var i:int = 0; i<p.length; i++) {
		graphics[p[i][0]].apply(graphics,p[i].splice(1));
	}
}

The above creates a function called render() that takes a 2D array of Graphics class methods and then runs them. This is a very interesting technique, specifically if you’d like to write Graphics class method calls in an XML or txt file and then have them run on a given DisplayObject in flash.

I’ve been thinking about the best way to do this for awhile… I started off doing something very convoluted and then realized that I could use Function.apply()….

Tomorrow I’ll post a snippet showing how to use this function in conjunction with XML.

2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *