Stroep

Just a collection of random works – Mark Knol

Tag Archives: snippet

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 , , , , .

Quick post here. I’d like to share this very quick way to create an automatic ID or index to your class instances. Mostly I pass an index as parameter to the class instance, or I use a public var to set the index. Using this way it is very easy to create an automatically filled index, since you have to set this up once and never worry again :)

Take a look at this code:

package
{
  public class MyObject
  {
    private static var global_index:int = 0;
    public const INDEX:int = global_index ++;
  }
}
 

As you see, I have created a static variable global_index, which is always the same to all MyObject classes. I also created a public constant ‘INDEX’, which would be unique in every instance. When the MyObject instance is created the index will be set to the global_index, and the global_index will increase by one. So that’s basically the trick to create the auto-increment index for your AS3 class.

update: Changed global_index to a private static + removed constructor

Tagged with , , .

Multiple keys made easy with DictionaryQuick post here, a simple solution I found to have multiple keys enabled. Maybe most real game developers know better or more elegant solutions, but I found this useful enough to share it with you.

Here we go. Add these variable to your class. This is a Dictionary, which allows you to associate a value with an object key.

private var currentKeys:Dictionary = new Dictionary();
 

Then, in your constructor or wherever you assign eventListeners, add these (well-known) listeners, with the callback functions:

import flash.events.KeyboardEvent;

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);

private function onKeyDown(e:KeyboardEvent):void
{
    currentKeys[e.keyCode] = true;
}
       
private function onKeyUp(e:KeyboardEvent):void
{
    currentKeys[e.keyCode] = false;
}
 

Inside your enterframe-event or timer (were you want to detect which keys are pressed), you could these kind of detection.

import flash.ui.Keyboard;
import flash.events.Event;

private function onUpdate(e:Event):void
{
    if ( currentKeys[ Keyboard.SPACE ] )
    {
        tank.shoot();
    }
    if ( currentKeys[ Keyboard.RIGHT ] )
    {
        tank.targetDirection -= 0.1;
    }   
    if ( currentKeys[ Keyboard.LEFT ] )
    {
        tank.targetDirection += 0.1;
    }   
    if ( currentKeys[ Keyboard.UP ] )
    {
        tank.speed += tank.acceleration;
    }   
    if ( currentKeys[ Keyboard.DOWN ] )
    {
        tank.speed /= 1.8;
    }
}
 

I found that if you use some 3 or 4+ combinations of keys at the same time, the keyboard events are not triggered anymore, which is a bit of annoying bug in the FlashPlayer. I mean pressing forward and left and shooting at the same time could be a problem? Well; Hope this helps, I think its very easy and a great usage of the Dictionary.

Tagged with , , .

I’ve updated my Image class. It is irritating flashsites break the right-click contextmenu. Well, I can’t fix that and Adobe should look at that, but I think it would nice to add some of the browser – features to my image class.

Currently I have these options added to the Image class:

View image
Views image in new window/tab. I used NavigateToURL to make this happen.

Save Image as..
Saves image on your computer. I used my ImageClass.saveLocal() to make this happen. This is only available within FP10, but I think this is no problem anymore because < a href = "http://www.adobe.com/products/player_census/flashplayer/version_penetration.html" > 93 % (September 2009) has FlashPlayer 10, so most people have it, and I don’t support outdated software ;)

Copy Image location
Copies the url to the clipboard, using System.setClipboard(url). It’s a pity I can’t create a ‘Copy Image’ function, because pushing bitmapdata into the clipboard is only supported in AIR.

Send Image
Sends the url to the mail-client, using “mailto:&body=” + src. Also a pity; I can’t add the image directly into the mail.

How to enable the contextmenu:

import nl.stroep.utils.Image;

var myImage:Image = new Image("myImage.jpg");
myImage.enableContextMenu = true; // enable it!
this.addChild(myImage);
 

I still love this class, I use it a lot. I want to encourage you to please add these kind of usability things to your apps / websites. And share them! Yes, it takes some extra time to create/add it, because this IS the finishing touch, but a lot of people will like this kind of features.

Download
Check out the Image class atgooglecode

Tagged with , , .

Code snippetI found out the getBounds()-function gives not exactly the right rectangle with a TextField. It always matches the border bounds, even if the borders are invisible. So I’ve created a more accurate function using getColorBoundsRect().

Click on the words. Switch between getRect() and getTextFieldBounds() by clicking on the buttons below to see the difference.

» Download source

Tagged with , .

Square rootFound out something useful, which I’d like to share with you. It’s about calculating the width of menu-items perfectly.

Imaging you are creating a liquid website with a menu. If you want all items to have the same width, you could set the width of each item to totalMenuWidth / items.length. In most cases this will work out. But what is your menu is very small or the items doesn’t fit in that fixed width because the text is too long?

Well you could hardcode the width’s to make your own perfect proportions and spacing, but if your menu is xml-driven and you/someone else adds new menu-items, you have to re-assign the hardcoded widths and you feel unhappy :) Most hardcoded stuff is evil anyway because it is laziness. (I use it a lot :P )

Well, I’d like to calculate the perfect scaling menu, so I don’t have to worry the menu will break. You can use the text-length of the menu-item as input for the width calculation. The more letters, the bigger the menu-item, right? So, If you multiply all menu-text-lengths and divide this to the current text-length, you’ll get a ratio which can be divided from the total menu width. I like this theory. So we need to do this in 2 steps; first get the ratios and get the total menu-text-lengths (with a loop), then calculate and apply this on each item.
Pseudocode:

itemwidth = fullMenuWidth / (totalTextLength / menuitem.text.length)

This works fine, and its actually very cool. Now we have a function which actually use some proportions to create a liquid menu. After a while I realized that the proportions weren’t really right. If the menu text have odd text-length differences (eg 5 letters vs 25 letters), it looks weird. Larger texts take too much width. I wanted the same proportions kinda like a html-table.

So the menu-items needs to have better proportions. Bigger text should be a smaller and the smaller text should be bigger. After some searching I ‘discovered’ Square root, a.k.a. Math.sqrt() in actionscript. With this function you could ‘normalize’ numbers. Bigger numbers are getting smaller, smaller numbers are getting bigger. This was exactly what I needed!

You can see the result below:

You can see the differences between the menubars and you’ll agree to me that the last one is the best :) I think this theory could be applied to a lot more things, like graphs or grids.

In case anyone is interested in the code; it can be downloaded here (AS3).

Tagged with , , .

Quick post; How to crop a bitmap / displayobject / Movieclip / Sprite or just the stage with Flash/AIR/AS3.

function crop( _x:Number, _y:Number, _width:Number, _height:Number, displayObject:DisplayObject = null):Bitmap
{
var cropArea:Rectangle = new Rectangle( 0, 0, _width, _height );
var croppedBitmap:Bitmap = new Bitmap( new BitmapData( _width, _height ), PixelSnapping.ALWAYS, true );
croppedBitmap.bitmapData.draw( (displayObject!=null) ? displayObject : stage, new Matrix(1, 0, 0, 1, -_x, -_y) , null, null, cropArea, true );
return croppedBitmap;
}
 

Usage:

var myCroppedImage:Bitmap = crop( 100, 100, 200, 200 );
this.addChild ( myCroppedImage );
 

Download

» Download CropUtil class on googlecode.

ps. To save the capture, use the ImageSaver class

Tagged with , .