Stroep

Just a collection of random works – Mark Knol

Tag Archives: as3

Recently I found an interesting question on FlashFocus.nl, about creating light and shadows in a 2D environment. I started experimenting with this to see how far I could take it. I love to share the results and some insides about this fun project.

How to get started

The initial code that the topic starter used a loop through all objects, and used hitTestPoint-function to detect if the light hits a wall. Therefore he used a loop with 360 steps, used for all directions. In the innerloop it tries if it hits the wall, otherwise goes away from the light (using the direction of the outerloop), tries if it hits the wall. That loop goes on till it does hit a wall. It is a bit of trial and error, but I think it is very clever. At the end of each loop a lineTo is used to draw the light, so in the end it will be a shape with 360 vector points.

Speed of light

Now, that screams for optimization and speed. It’s a fun project to mix some things you have seen and want to try out for a long time. The first thing that I tried to make it faster, draw all objects into an BitmapData, and use the getPixel function instead of hitTestPoint, which is notable faster if you don’t move objects. I used that BitmapData object only too check if the light hits the objects; no one actually sees it. To use hitTestPoint, you must loop through all objects and detect if they hit. With a lot of objects, it would be slower. With BitmapData, you don’t need that loop, and you are free to use unlimited objects with even custom shapes. Less looping == faster, unlimited objects == awesome :)

More realism

I also wanted to make it look more realistic. Having light only is not close enough to realism. It needs shadows. I created an inverted shape of the light-shape and filled it with black (a). This creates a nice shadow, however has very hard bounds, which is ugly. So then I took the shape again and drawed with a nice transparent to black gradient (b). Those 2 layers have the BlendMode ALPHA. The holder of those has a solid shape fill (as big as the stage) with BlendMode LAYER. This creates a nice ‘hole’ which I think works very well as shadow if you make it half-transparent. Oh, the colored light-layer (c) is a gradient too, with the same shape as b, only with BlendMode ADD.

Re-using shape data

Another optimization I used was to use graphics data API. In this case I have 1 shape which could be reused 3 times. So before even drawing, I collect all points and commands in an Vector. When I have all data collected, it draws the light-layer and shadow-layer at first, then it pushes some extra points to the Array to make the outer shadow-layer. So with 1 Array of (manipulated) data I could draw multiple shapes. That’s a good case of using the graphics data, I guess.

Optimized trig functions

I also used the TrigLUT-class (Trigonometry LookUp Table) from jacksondunstan.com, since the loop heavily uses Math.sin and Math.cos. I could use the valNormalizedPositive() function from that class in this case. It’s very fast and for me it was fun to use that class. :D

But it is still too slow..

The most intense about this thing isn’t the calculation, but the rendering itself. The whole ‘canvas’ needs to be updated and redrawed every frame with lots of layers and blendmodes, which is very intense for the CPU. I don’t know if this would be possible with Stage3D, but that would be the last step to render really fast. And when that is possible, I’ll guess I could move the object real-time too, which makes it very interesting for games.

Check out the experiment:
» Lights and shadows

Let me know what you think about it and how does it perform on your computer?

Tagged with , , , .

Design pattern – Behaviors (7)

October 16th, 2011, under actionscript.

Design pattern - BehaviorsI recently started working at MediaMonks where they are using this interesting pattern of coding; behaviors as a class. I started playing with ‘behaviors’ myself to see how this could work for me. If you use this pattern once, you’ll wonder why you did not use it ever before ;) This post will lead you through some examples and shows some benefits of using it. This post is written with focus on actionscript 3 developers, who can read code and knows already something about object oriented programming. The goal is to learn more and become a better developer.

What is a behavior?

Well I guess everybody knows what it means, but in terms of code I would say that a behavior-class is some kind of a simple controller with a target. It does one thing, it controls the target with a specific feature/goal. The idea is to add functionality by assigning a behavior to an object (composition), instead of extending it to get the functionality (inheritance). That sound complicated, so why not check out what it practically means?

Difference between inheritance and composition

Let’s say you want to program an object that follows your mouse. How would you create it? I would create a class named MouseFollowingSprite which has all functions to do that. Then I would extend or create an instance of that MouseFollowingSprite-class and BANG I’m done :)

Typical example of inheritance

class MouseFollowingSprite extends Sprite

Okay, lets write down that killer class:

package nl.stroep.display
{
    import flash.display.Sprite;
    import flash.events.Event;
   
    /**
     * @author Mark Knol
     */

    public class MouseFollowingSprite extends Sprite
    {
        private var _ease:Number;
       
        public function MouseFollowingSprite()
        {
            init();
        }
       
        private function init():void
        {
            this.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
        }
       
        private function handleEnterFrame(e:Event):void
        {
            update();
        }
       
        private function update():void
        {
            this.x += (this.mouseXthis.x) / _ease;
            this.y += (this.mouseYthis.y) / _ease;
        }
    }
}
 

(You see that? It’s nicely done with some eased motion :D )

I have never seen a problem with extending, but I had troubles with finding a good way to add other kind of functions to this type of classes. In terms of OOP, is a rule to write classes with a single responsibility, and we already passed that one. But imaging you want your mouse following sprite also to scale when you scroll with your mouse wheel. Well that would be easy: Just create a class named ScrollWheelScalingSprite, which extends MouseFollowingSprite. Now it has both functionality, when you would create an instance of it.

Let’s create our ScrollWheelScalingSprite, it would like this:

package nl.stroep.display
{
    import flash.display.DisplayObject;
    import flash.events.Event;
    import flash.events.MouseEvent;
   
    /**
     * …
     * @author Mark Knol
     */

    public class ScrollwheelScaleSprite extends MouseFollowingSprite
    {
        private var _ease:Number;
        private var _targetScale:Number;
        private var _hasListener:Boolean;
        private var _deltaRatio:Number = 0.1;
        private var _minimum:Number = NaN;
        private var _maximum:Number = NaN;
       
        public function ScrollwheelScaleSprite()
        {
            _targetScale = this.scaleX;
           
            init();
        }

        private function init():void
        {
            stage.addEventListener(MouseEvent.MOUSE_WHEEL, handleMouseWheel);
            addEnterFrameListener();
        }
       
        private function handleMouseWheel(e:MouseEvent):void
        {
            _targetScale += e.delta * _deltaRatio;
           
            if (!isNaN(_minimum) && _targetScale < _minimum) _targetScale = _minimum;
            else if (!isNaN(_maximum) &&_targetScale > _maximum) _targetScale = _maximum;
           
            addEnterFrameListener();
        }
       
        private function addEnterFrameListener():void
        {
            if (!_hasListener)
            {
                this.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
                _hasListener = true;
            }
        }
       
        private function removeEnterFrameListener():void
        {
            this.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
            _hasListener = false;
        }
       
        private function handleEnterFrame(e:Event):void
        {
            update();
        }
       
        private function update():void
        {
            this.scaleX += (_targetScale – this.scaleX ) / _ease;
            this.scaleY = this.scaleX;
           
            if (Math.abs(this.scaleX – _targetScale) < .01)
            {
                removeEnterFrameListener();
            }
        }
    }
}
 

Let’s go some deeper. What if you want a ScrollwheelScaleSprite which should not follow our mouse? That would be a problem, because it already has that functionality. However you could hack around around by adding some protected booleans, to enable the actual functions of the class. Name them like _mouseFollowingEnabled. When your class extend some other classes, you’ll probably need a _scrollWheelScalingEnabled too. In the constructor of the new class you just turn on/off the booleans and your done. But then again, if you want to use this to Bitmap, you have a problem, you cannot extend a Sprite and a Bitmap at the same time.

I mean, this is how we code, right? All classes have one responsibility, but could this example been done better? While writing, this post reminds me in a way to this older post of Keith Peters; you should read it. It also has a interesting discussion.

Create behaviors

As already stated, a behavior class is a controller. It deals with an object (we call it target) to add the actual behavior. Now I don’t think extending is bad, but I think we should use it with care.

Let’s create an abstract behavior class, which can be extended. (This is not needed, but very helpful for accessing the target and prevent duplicate code)

package nl.stroep.behaviors
{
    import flash.display.DisplayObject;
   
    /**
     * @author Mark Knol
     */

    public class AbstractBehavior
    {
        protected var _target: DisplayObject;
       
        public function AbstractBehavior(target: DisplayObject)
        {
            this._target = target;
        }
    }
}
 

I think this does not require lots of explanation. We have a class, it saves a target
that is passed from the constructor. We can do lot’s of stuff inside a behavior from this point.

Now, let’s convert our MouseFollowingSprite to a MouseFollowingBehavior, which should extends the AbstractBehavior. Most drastic change is to convert ‘this‘, to ‘_target‘ and change the constructor to make it an actual behavior:

package nl.stroep.behaviors
{
    import flash.display.DisplayObject;
    import flash.events.Event;
   
    /**
     * @author Mark Knol
     */

    public class MouseFollowBehavior extends AbstractBehavior
    {
        private var _ease:Number;
       
        public function MouseFollowBehavior(target: DisplayObject, ease:Number = 5)
        {
            super(target);
           
            _ease = ease;
           
            init();
        }
       
        private function init():void
        {
            _target.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
        }
       
        private function handleEnterFrame(e:Event):void
        {
            update();
        }
       
        private function update():void
        {
            _target.x += (_target.mouseX_target.x) / _ease;
            _target.y += (_target.mouseY_target.y) / _ease;
        }
    }
}
 

This is not magic, but it is very powerful. We can assign this behavior to a Sprite, but also to a Bitmap or Video etc. This would not that easy / possible with inheritance only. The class works standalone and we don’t need booleans to enable or disable the behavior.

Ok, let’s also create the scroll wheel scale behavior:

package nl.stroep.art.behaviors
{
    import flash.display.DisplayObject;
    import flash.events.Event;
    import flash.events.MouseEvent;
   
    /**
     * …
     * @author Mark Knol
     */

    public class ScrollwheelScaleBehavior extends AbstractBehavior
    {
        private var _ease:Number;
        private var _targetScale:Number;
        private var _hasListener:Boolean;
        private var _deltaRatio:Number;
        private var _minimum:Number;
        private var _maximum:Number;
       
        public function ScrollwheelScaleBehavior(target: DisplayObject, ease:Number = 5, deltaRatio:Number = 0.1, minimum:Number = NaN, maximum:Number = NaN)
        {
            super(target);
           
            _ease = ease;
            _deltaRatio = deltaRatio;
            _minimum = minimum;
            _maximum = maximum;
            _targetScale = target.scaleX;
           
            init();
        }
       
        private function init():void
        {
            _target.stage.addEventListener(MouseEvent.MOUSE_WHEEL, handleMouseWheel);
            addEnterFrameListener();
        }
       
        private function handleMouseWheel(e:MouseEvent):void
        {
            _targetScale += e.delta * _deltaRatio;
           
            if (!isNaN(_minimum) && _targetScale < _minimum) _targetScale = _minimum;
            else if (!isNaN(_maximum) &&_targetScale > _maximum) _targetScale = _maximum;
           
            addEnterFrameListener();
        }
       
        private function addEnterFrameListener():void
        {
            if (!_hasListener)
            {
                _target.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
                _hasListener = true;
            }
        }
       
        private function removeEnterFrameListener():void
        {
            _target.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
            _hasListener = false;
        }
       
        private function handleEnterFrame(e:Event):void
        {
            update();
        }
       
        private function update():void
        {
            _target.scaleX += (_targetScale – _target.scaleX ) / _ease;
            _target.scaleY = _target.scaleX;
           
            if (Math.abs(_target.scaleX – _targetScale) < .01)
            {
                removeEnterFrameListener();
            }
        }
    }
}
 

Now we can assign a behavior very easy:
Example of applying the behaviors

var sprite:Sprite = new Sprite();
new MouseFollowBehavior(sprite);
new ScrollwheelScaleBehavior(sprite);

You are now free to add the behaviors you’ll need, and leave the one you don’t need. It’s like creating little plugins. Fun eh? It’s nice to add parameters to the constructor, to make it less static. The other fun part is that if you build a behavior right, you could copy/paste it to another project or in you library, because it has no dependencies to classes you don’t want or need. Of course, this is not something new, you could have seen this in temple-lib but also the Hype-framework too, and maybe lots of other framework probably use this pattern in a way.

Now we know the difference:
Inheritence: “I want a Sprite that follows my mouse”
Behaviors: “I want something that makes a Sprite follow my mouse”

Killing the behaviors

The code examples in this post does not have any function to remove it, but if you want to remove a behavior, it would be wise to assign the behavior to a variable, and create a destruct() or destroy() function inside the behaviors to remove listeners and references to the target etc, and then set it to null.

// Anywhere in your code:
var myBehavior:MouseFollowBehavior = new MouseFollowBehavior(myMc);

// Somewhere in your code where you want to remove the behavior:
myBehavior.destroy(); // a public function which removes all listeners, references etc
myBehavior = null;
 

Conclusion

Behaviors are a cool and give clean reusable classes and I think we should use it more. It’s probably not new for you and the inheritence-example is not very realistic, but I hope it’s refreshing to look at it again. If you want to learn more design patterns, I also recommend this site.

If you think back on how you have coded in the past, what would you change now you know this pattern? BTW I want to learn more too, so don’t hesitate to leave some nice feedback below.

Oh, maybe you haven’t heard, but something unexpected will happen if you hold CTRL and click on the facebook like-button (found that in a YouTube comment; very lame).

Tagged with , , .

Finally I have created and finalized my Actionscript 3 Event Generator, which was buggy but now it is very nice :) As stated on twitter, if you are a flashdeveloper and use custom events in actionscript 3, you should use this tool because it helps you create custom event classes very fast.

Features:
- Fast variable adding
- Event type generation (static constants). Just use lower camelCased variables and they will be formatted nicely.
- Meta data for a event dispatcher class.
- Automatic clone() function
- Automatic toString() function

URL
» http://projects.stroep.nl/EventGenerator/

Don’t forget to first fill your name at @author on the right. The package and @author will be saved for next time.

I have also created a dropdown-menu on the top-right to switch to other tools. Happy coding!

Tagged with , , , .

I created a tool to created ‘grouped’ value objects nicely and very fast. It is using private classes. I found it useful enough to share it with you, so maybe if you are in need of such a tool, you are free to use it.

» Check it out: http://projects.stroep.nl/enumGenerator/

Oh, if you want to create normal value objects, use the value object generation tool. For creating custom events classes, I have an custom event generator.

Tagged with , , , .

I am working on a Pie-chart class. Data visualisation is fun, so I want to create my own pie-chart. Reinventing the wheel (creating another pie-chart) is a good thing if you want to create a custom wheel, so you know how to modify to make it fit your needs. Now this post is not about the pie-chart, but about something I discovered inside the graphics class. Most flashcoders knows you can draw lines using graphics.lineTo. There is another way of drawing lines in actionscript, using the graphics.drawPath and graphics.drawGraphicsData function. Let’s take a look at it.

graphics.lineTo

The good old method. Drawing a line from point (x:100, y:150) to point (x:300, y:300). Check out these four lines of clear code.

graphics.clear(); // start with blank canvas
graphics.lineStyle(2, 0xFF9900);
graphics.moveTo(100,150);
graphics.lineTo(300,300);
 

graphics.drawPath

Now, you could also use this alternative way of drawing. There is no such thing as creating circles or squares using this method, only manual. It is using commands (moveTo, lineTo, curveTo) and has a separate list of data containing the actual values. All values in the data-list represents the x-positions (odd values) and y-positions (even values). So we are pushing x, y, x, y etc.
When using CURVE_TO, you need to define four values; controlX, controlY, x, y. Take a look at the code:

var commands:Vector.<int> = new Vector.<int>();
var data:Vector.<Number> = new Vector.<Number>();
commands.push(GraphicsPathCommand.MOVE_TO, GraphicsPathCommand.LINE_TO); // add 2 commands, moveTo and lineTo
data.push(100, 150)
data.push(300, 300); // push all values into data-list

graphics.clear(); // clear the canvas
graphics.lineStyle(2, 0xFFCC00); // Set the stroke style
graphics.drawPath(commands, data); // finally, draw it all
 

As you could see, you need to write a bit more code. As you can see you can combine the graphics.lineStyle and the graphics.drawPath functions, so its not completely new.

By the way, did you know you could push multiple items to an list at a time?

graphics.drawGraphicsData

Be prepared, 12 lines to draw the same a line.

var commands:Vector.<int> = new Vector.<int>();
var data:Vector.<Number> = new Vector.<Number>();
var path:GraphicsPath = new GraphicsPath(commands, data);
var drawing:Vector.<IGraphicsData> = new Vector.<IGraphicsData>();

var stroke:GraphicsStroke = new GraphicsStroke(2);
stroke.fill = new GraphicsSolidFill(0xFF9900);
// The stroke definition with a fill

commands.push(GraphicsPathCommand.MOVE_TO, GraphicsPathCommand.LINE_TO); // add 2 commands, moveTo and lineTo
data.push(100, 150)
data.push(300, 300); // push all values into data, odd represents the x-positions, even represents the y-positions. So we are pushing x, y, x, y etc.
drawing.push(stroke, path); // collect all data inside one list

graphics.clear(); // clear the canvas
graphics.drawGraphicsData(drawing); // finally, draw it all
 

The drawGraphicsData function forces you to push all data into a new list. The fun thing is, you feel very exited when you have the last example running. I don’t know why, but getting advanced stuff working feels good. Note, for the last example we need to import these classes to draw that orange line. Five classes for one simple orange line, pretty impressive eh? :)

import flash.display.GraphicsPath;
import flash.display.GraphicsPathCommand;
import flash.display.GraphicsSolidFill;
import flash.display.GraphicsStroke;
import flash.display.IGraphicsData;
 

Borders/fills

When I first started to use this way of drawing lines, I noticed that I needed 2 lines of code to define a stroke. The fill is the last parameter of the GraphicsStroke class, and I really dislike to define all other optional parameters just to set that one parameter at the end. Oh, without a fill or color, a border is invisble ;) Still don’t get it! The fill is a fun part of this advance drawing method. Now in the normal lineTo-world we know these linestyles graphics.lineBitmapStyle, graphics.lineGradientStyle, graphics.lineShaderStyle and ofcourse the graphics.lineStyle. Now if you want to create a border to be ‘filled’ with something, you could create a GraphicsSolidFill, GraphicsGradientFill, GraphicsBitmapFill or GraphicsShaderFill.

It is nice to know the same classes could be used to fill a shape, so they could be added to the drawing-list too. That is really a nice part of this advanced way of drawing, just add or remove instances of classes to the drawing-list (it should implement IGraphicsData).

You can now define fills, strokes and multiple paths before you actually draw it on the stage.

Saving graphics; saving numbers

The cool thing of this whole advanced drawing method is that you could save the commands/paths as a file and redo it more easy than graphics.lineTo. If you do generative arts this could be a benefit. There is no official function for saving the data, but you could write it yourself since we are dealing with numbers. When opening a file you could theoretically push all commands/paths/fills inside the drawing-list and you could draw the same drawing. I haven’t test this, but maybe you could save the whole vector as ByteArray using ByteArray.writeObject(), compress it and then you have a nice way of saving ‘graphics’. Another benefit, you could delay ‘the draw’ and still collect data which could be drawed later. Very handy if you are doing heavy generative arts.

Conclusion?

It is not easy to draw lines using the the advanced method, since you are dealing with vectors with numbers, instead of lines. It is cool to have every graphic-thing as a separate classes and fills are nicely done and easily swap-able. Graphics data is now more flexible. Adobe could add more graphics classes. I hope they will add support for custom strokes (like Illustrator). At the other side, most things still fit in the good-old lineTo coding-style, which is very clean and straight-forward. Anyhow, it is nice to see a new way of saving graphics.

When you are drawing lots of lines, this advanced way should bring better performance since it is delaying the actual draw. I haven’t benchmarked how much exactly, but since you can mix graphics.drawPath with graphics.lineStyle, it feels graphics.drawGraphicsData is syntactic sugar which has the benefits noted I already mentioned.

I also wonder if it there would be a performance boost if you create your own lineTo function (which only pushes data to a list) based on the graphics.drawGraphicsData, with one drawNow() function.

Hope this will inspire you to share other or new possibilities.

var theEnd:GraphicsEndFill = new GraphicsEndFill(); // thanks for reading
 

Tagged with , .

Optimized loops (12)

July 17th, 2011, under actionscript.

Optimized loopsEvery one should write code that performs well. Do you use loops in your code? This is a simple trick everyone could apply to his loops.

How you write a loop

Mostly when people are writing loops, it looks like this:

for(var i:int = 0; i < list.length; i++)
{
   var item:MyItem = list[i];
   item.doSomething();
   item.doAnotherThing();
}
 

Now this loops works, but there are some small things that could be improved. If you use lots of loops it should be needed to improve your loops, but I hope this is just nice to know anyway.

The optimized version

Take a look at the improved loop:

var item:MyItem;
var total:uint = list.length;
for(var i:uint; i < total; i++)
{
   item = list[i] as MyItem;
   item.doSomething();
   item.doAnotherThing();
}
 

What is improved in this loop? If you take a close look in both loops you will see I access the list-item once using list[i], and assign it to a variable called item. I don’t what it is, but for me it looks like most people who write javascript always use list[i] instead of creating a var of it, is that right? It is important to know you don’t need to create the var inside the loop, but create it once outside the loop, and (re-)use it while looping. I forget this most of the times, but it is a good practice to check if all the variables you are using inside a loop. Most of the times variables could be defined outside the loop, which could increase performance big time.

The second thing is to define a variable called total, which pre-calculates the length of the loop as a local variable. If you don’t define it, the FlashPlayer checks the length of the Array every time in the loop, now it is like a constant. Note, when you are removing items from the list, you should ajust the total-variable too, since the total does not equal the length of the list anymore ofcourse. ;)

Another thing you probably noticed is that I used the ‘as’ keyword to give the FlashPlayer a direct hint of the type of variable. This another way of casting, and slightly faster than MyItem(list[i]).

Update: Take a look at this great article about the performance of this casting method. http://jacksondunstan.com/articles/1305

Some other small things are to use uints for i and total in loops if you are using positive numbers. Another small thing is that you don’t have to define i = 0, only when you are using nested loops or re-using the i or j in the same function/scope.

Want a more freaky way to define the same optimized loop?

for(var i:uint, item:MyItem, total:uint = list.length; i < total; i++)
{
   item = list[i] as MyItem;
   item.doSomething();
   item.doAnotherThing();
}
 

Are you using FlashDevelop? You could this for-loop snippet (scroll down).

Most of the loop-optimisation tips also applies to javascript.

Tagged with , , .

This article is some training for your JavaScript skills. I love Actionscript , and I am also starting to like JavaScript. However, coding in JavaScript feels like Actionscript 1.0. It’s a pity there aren’t decent editors, especially if you want to write object-oriented-code, which is possible with JavaScript . At the moment I think VisualStudio is the best JavaScript editor, but I really wish there was a tool for JavaScript like FlashDevelop (a clean editor for Actionscript projects) with great intellisense, code completion and snippets etc. But we should not focus on tools, lets focus on the language and get the most out of it. HTML5 is an hot topic today, and it seems using JavaScript is an important part of it, so why not learn more of it? I have seen some stunning HTML5 examples over the last year. As a developer it is very interesting to see how others code JavaScript. By the way; Personally I find it very funny to see how JavaScript has changed it’s ‘image’. Some of us remember the good days in Netscape. JavaScript was .. *kuch* not fast and associated with ugly rainbow mouse pointers and aggressive popup screens. Now it is associated with HTML5, which is supposed to be the future and it will be bright ;) I refuse to put my opinion about this topic here.
I think the ‘image’ of JS has slowly changed after great frameworks like jQuery have reached the developers. jQuery is awesome, I advice to use jQuery as default in all sites/apps.

Anyway, there are (ofcourse) some techniques to code like Actionscript in JavaScript. These snippets have helped me to understand object oriented JavaScript. For too long I did not even tried to learn what was possible with JavaScript because I thought it was a very limited language. Maybe some information is outdated; I am still learning, so please share your feedback.

Object oriented javascript

In javascript it is possible to create classes, public and private vars, getters/setters and there are even constructors. A function could be seen as a class. This is a bit strange at first, but if you use it for a while you will understand. Now lets create our own class right now.

Lets port some stuff of this Color Class to javascript. It has private vars and public functions.

Declare classes

Defining classes is as easy as defining functions, because it is almost the same. After creating an function, you could already make some instances of it. The example below creates a Color class with a public variable called value. After that we create 2 instances of the Color class with some other values.

Note: I use the same code conventions as Actionscript: Classes should be UpperCased, functions/vars should be lowerCased and constants should be FULL_CAPS. Oh and since javascript looks like as1.0, I sometimes use an underscore before private vars :P

function Color( value )
{
    this.value = value || 0;
    alert("Color created with value: " + value)
}

var myRedColor = new Color(0xFF0000); // create instance of Color  (a red one)
var myOrangeColor = new Color(0xFFCC00); // create instance of Color  (an orange one)
alert( myRedColor.value );
alert( myOrangeColor.value );
 

Public / Private

In actionscript it is very useful to use encapsulation, which is a mechanism for restricting access to other objects. The previous+following example should work in all browsers. The difference between public and private vars/functions in javascript can be declared like this:

function Color( value )
{
    // public variable
    this.value = value || 0xFFFFFF; // set default value to 0xFFFFFF for parameter if it isn’t defined

    // private variable
    var _name = "test";

   // public function
   this.getRandomColor = function( )
  {
     return Math.random() * 0xFFFFFF;
  }

  // private function
  function getNiceColor()
  {
     return 0xffcc00;
  }
}

// create instance of Color
var color = new Color(0xFF0000);
alert( color.value ); // returns red color
alert( color.getRandomColor() ); // returns random color

// not possible :
alert( color.getNiceColor() ); error in console; property does not exist, because function is private.
alert( color._name ); // error in console; property does not exist, because variable is private.
 

I think with this principles (maybe in combination with namespaces, see below) you can create clean javascript code.

Packages > Namespaces

Now before using classes in javascript I had some conflicts with function and variable names because there were unwanted duplicates. I have written a little helper tool to use namespaces. It helps to prevent those conflicts. Now it looks more like Actionscript 3, only there is no such thing like ‘imports’. This snippet works in all browsers.

/// create namespace like ‘com.yourcompany.projectname’
function Namespace(namespace)
{
    var parts = namespace.split(".");
    var root = window;
    for(var i = 0; i < parts.length; i++)
    {
        if(typeof root[parts[i]] == "undefined")
        {
            root[parts[i]] = {};
        }
        root = root[parts[i]];
    }
}

// creating my own namespace here
Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function(value) // create class inside package
{
  this.value = value || 0xFFFFFF;
}

var myRedColor =  new nl.stroep.utils.Color(0xff0000);
alert(myRedColor.value);
 

Getters and Setters

Now it is possible to use getters and setters. NOTE (!): Ofcourse this method does not work in IE, so this is pointless but also a bit cool to see how far we could go. Anyway there are 2 ways to define them. Read more about it here. I think the __defineGetter__ way is better; it looks ugly but you still have access to private objects.

Take a look at this getter/setter declaration example. It’s not as clean as AS3 getters/setters but it works like a charm in my browser.

function Color( value )
{

   /* public getter */
   this.__defineGetter__("value", function()
   {
        alert("getter called; current value: " +value);
        return value;
    });
   
   /* public setter */
   this.__defineSetter__("value", function(val)
   {
        alert("setter called; new value: " +val);
        value = val;
    });
   
   // public variable. For a strange reason I have to put this below the get/set definition.
   this.value = value || 0xFFFFFF;
}

// create instance of Color
var color = new Color(0xFF0000);
color.value; // getter
color.value = 0xff0000; // setter
 

Constants

Javascript has a const too, you could use it instead of var. Ofcourse this is not implemented in IE, so it is also pretty pointless to use.

Mix them all

Now lets use namespaces, getters/setters and private/public variables and functions together.
This is a simplified ported version of this Color Class.
With this class you can modify the red,green and blue channels of a color individually. In the original class it is possible to lighten/darken the color too, but for this post I left these functions, because this only illustrates the possibilities of nice OO javascript.

Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function( color )
{   
    /* PUBLIC FUNCTIONS */
   
    this.grayscale = function( val )
    {
        val = val || 0;
        if (val < 0){ val = 0 }
        if (val > 255) { val = 255 }
       
        return (val << 16) | (val << 8 ) | val;
    }
   
    /* PRIVATE FUNCTIONS */
   
    function limit( val, lowerLimit, upperLimit )
    {
        if (val < lowerLimit){ return lowerLimit }
        if (val > upperLimit) { return upperLimit }
        return val;
    }
       
    /* PUBLIC GETTER FUNCTIONS */
   
    this.__defineGetter__("value", function()
    {
        return (_red << 16) | (_green << 8 ) | _blue;
    })
   
    this.__defineGetter__("red", function()
    {
        return _red;
    })
   
    this.__defineGetter__("green", function()
    {
        return _green;
    })
   
    this.__defineGetter__("blue", function()
    {
        return _blue;
    })
   
    /* PUBLIC SETTER FUNCTIONS */
   
    this.__defineSetter__("value", function(val)
    {
        _red  = val >> 16 & 0xFF; // red
        _green  = val  >> 8 & 0xFF; // green
        _blue = val & 0xFF; // blue
       
        _value = val;
    })
   
    this.__defineSetter__("red", function(val)
    {
        _red = val;
        _red = limit( _red, 0, 255 );
    })
   
    this.__defineSetter__("green", function(val)
    {
        _green = val;
        _green = limit( _green, 0, 255 );
    })
   
    this.__defineSetter__("blue", function(val)
    {
        _blue = val;
        _blue = limit( _blue, 0, 255 );
    })
   
    /* PRIVATE VARIABLES */
    var _value = color;
    var _red;
    var _green;
    var _blue;
   
    /* PUBLIC VARIABLES */
    this.value = _value;
   
};
 

With this javascript class, you could use it like this:

var color = new nl.stroep.utils.Color(0xFFCC00) // define orange.
color.green = 0; // remove green.. now it is red..
color.blue = 255; // add some blue.. now it is purple..
alert(color.value.toString(16)) // alerts FF00FF and that is purple.
 

Hope you enjoyed this article. Feel free to share or comment.

Tagged with , , , , .