Graphics Class Methods in XML

Actionscript:
  1. // for simplicity I left this XML inline, this will work exactly the same if it were external
  2. var program:XML=<body>
  3.                 <draw>
  4.                   <![CDATA[
  5.                    beginFill(0xFF0000);
  6.                    drawCircle(100,100,50);
  7.                    endFill();
  8.                    lineStyle(0, 0x666666);
  9.                    moveTo(100, 100);
  10.                    lineTo(200, 200);
  11.                    moveTo(300, 200);
  12.                    curveTo(350, 300, 400, 200);
  13.                    lineStyle(0, 0x0000FF);
  14.                    drawRect(200, 50,100,100) ;
  15.                     ]]>
  16.                 </draw>
  17. </body>;
  18.  
  19. // parse and run the Graphics class commands from the XML
  20. render(parseFunctions(program.draw.toString()));
  21.  
  22. function parseFunctions(dat:String):Array{
  23.     var a:Array = dat.split(";") ;
  24.     for (var i:int = 0; i<a.length-1; i++){
  25.         a[i] = a[i].split(/\(\)|\(|\)/g);
  26.         var f:String = a[i][0] = a[i][0].replace(/\s/g,"");
  27.         a[i] = a[i].splice(0, a[i].length - 1);
  28.         if (a[i].length> 1){
  29.          a[i] = a[i][1].split(",");
  30.          a[i].unshift(f);
  31.         }
  32.     }
  33.     return a.splice(0,a.length - 1);
  34. }
  35. function render(p:Array):void {
  36.     for (var i:int = 0; i<p.length; i++) {
  37.         graphics[p[i][0]].apply(graphics,p[i].splice(1));
  38.     }
  39. }

The above code builds on yesterdays post by showing how one could potentially store graphics class method calls in XML using a few regular expressions and Function.apply().

The parseFunctions() function reads through the CDATA string and formats it in a 2D array that looks like this:

Actionscript:
  1. [[beginFill, 0xFF0000], [drawCircle, 100, 100, 50], etc...]

The render() function reads through this 2D array, using the first value of each nested array as the function and the remaining values as arguments...

As is this won't really work with most of the new fp10 graphics methods...

This entry was posted in Graphics, XML, dynamic, external data, functions, string manipulation, strings and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*