The b(ack)log

A visual haXe example

This example will show you how to create a simple maize-style background in haXe like the picture below:

First we need to create the maize graphic. We do this by extending the flash.display.Sprite class. Lets call the derived class MaizeBackground.

class MaizeBackground extends flash.display.Sprite
{
public function new()
{
super();
}
}

This will create an empty sprite that does not show anything. In order to add some graphics we must either add another flash.display.DisplayObject containing some graphics to the sprite (like a Bitmap, MovieClip or another Sprite) or we must draw something on this sprite using the graphics property of the sprite.

We are going to use the graphics property of the Sprite. So lets add a method called redraw to our class and use this to draw the maize. We should call to this method in the constructor:

class MaizeBackground extends flash.display.Sprite
{
public function new()
{
super();
redraw();
}

public function redraw()
{
graphics.beginFill(0xFFFFFF, 1.0);
graphics.drawRect(0, 0, 800, 600);

var color : Int = 0x000000;
for (y in 0...60)
{
color = color ^ 0xFFFFFF;
for (x in 0...80)
{
var prev = false;
if ( Math.random() {
graphics.beginFill(color, 1.0);
prev = true;
}
else
{
graphics.beginFill(color ^ 0xFFFFFF, 1.0);
prev = false;
}
graphics.drawRect(x*10, y*10, 10, 10);
}
}

var filterArray = new Array();
filterArray.push(new flash.filters.BlurFilter(5, 5, 9));
filters = filterArray;
}
}

The logic for the redraw method is reasonably straight forward. We look at the maize as being divided into rows and columns.

  1. Step through the image row by row.
    • Alternate between black and white rows
    • For every column in the row there is a small possibility of drawing the inverted color.
    • Finally we apply a blur filter to make the crude maize look a little better.

</ol> An important thing to note is that the filters only get applied when we assign something to the filters property of a flash.display.DisplayObject. If we simply pushed the new BlurFilter to the filters property, the filter would not have been applied.

Save this class in a text file called MaizeBackground.hx

Now we need to create a main class and add the sprite to the stage. Create a class called MaizeExample:

class MaizeExample
{
static function main()
{
flash.Lib.current.addChild(new MaizeBackground());
}
}

Save this class in a text file called MaizeExample.hx

Finally we need to create a compile file for the haXe compiler and compile the swf. Create a file called compile.hxml with the following contents:


-swf maize.swf
-swf-version 9
-main MaizeExample

Save the file in the same directory as MaizeBackground.hx and MaizeExample.hx and run haxe in that directory.

This should produce a swf file that can be opened using Adobe’s flash player or browser plugin.

The MaizeBackground example could benefit from many improvements:

</ul> Any comments or suggestions are more than welcome!