Aug
07
2008

Javascript Colour Functions

I spent a couple of hours working through Mark Khan’s article on creating a colour picker widget in javascript. It’s a nice walk through, providing a good basis and a nice explanation of the technique used.

I thought I’d highlight a couple of useful generic colour functions in the code, as well as a couple I have written myself. The RGB to HSV conversion functions may be of particular interest to those who wish to extend the functionality of the colour picker in the original article.

Converting RGB to Hexcadecimal

I’d never really bothered to learn the relationship between RGB values and the hex code so often seen in CSS files. With a little investigation it appeared that it’s not that difficult a concept to grasp

In computing truecolour graphics describe 256 shades of Red, Green and Blue. This equates to somewhere in the region of 16 million different colours (256 x 256 x 256). Truecolor can be represent as three separate RGB values, such as 255, 255, 255 for white, but can also be described by a hexadecimal code such as #FFFFFF.

Hexadecimal is a base-16 numeral system. The symbols 0-9 and A,B,C,D,E,F represent values 0 - 15 respectively. Each truecolor RGB value maps very nicely to a two digit hexadecimal code as 16 x 16 = 256. Therefore in the white example #FFFFFF, each two digit code (FF) represents 255 for each of the of the RGB colour channels.

Converting an integer to a hex value is therefore very simple using javascript’s built in Integer.toString() method

/**
* Converts integer to a hexidecimal code, prepad's single digit hex codes with 0 to
* always return a two digit code.
*
* @param {Integer} i Integer to convert
* @returns {String} The hexidecimal code
*/
function intToHex(i) {
    var hex = parseInt(i).toString(16);
    return (hex.length < 2) ? "0" + hex : hex;
}

Converting in the other direction is unsuprisingly just as simple, this time using javascript’s parseInt() method. We need to precede our hex string with “0x” to tell the parseInt() method that the number is a hexadecimal. See the Mozilla javascript docs for more details.

/**
* Converts a hex number back to an integer, uses the javascript parseInt method
* with a base number (or radix) of 16. EG: parseInt("0x" + hex);
*
* @param {String} hex The hex code to convert
* @returns {Integer} The integer conversion of the hex number
*/
function hexToInt(hex) {
    return parseInt("0x" + hex);
}

Converting RGB to HSV

Hue, Saturation and Value (or Hue, Saturation and Brightness) is a common way of representing points within the RGB truecolor spectrum. These conversion functions were not present in the original colour picker article but their addition will give us some useful functionality.

Not being particularly gifted in mathematics I won’t attempt to explain in detail what’s going on here. I based these equations on the Wikipedia article for HSV, I suggest anybody wanting a deeper understanding of the concept start there.

/**
* Converts HSV to RGB value.
*
* @param {Integer} h Hue as a value between 0 - 360 degrees
* @param {Integer} s Saturation as a value between 0 - 100 %
* @param {Integer} v Value as a value between 0 - 100 %
* @returns {Array} The RGB values  EG: [r,g,b], [255,255,255]
*/
function hsvToRgb(h,s,v) {

    var s = s / 100,
         v = v / 100;

    var hi = Math.floor((h/60) % 6);
    var f = (h / 60) - hi;
    var p = v * (1 - s);
    var q = v * (1 - f * s);
    var t = v * (1 - (1 - f) * s);

    var rgb = [];

    switch (hi) {
        case 0: rgb = [v,t,p];break;
        case 1: rgb = [q,v,p];break;
        case 2: rgb = [p,v,t];break;
        case 3: rgb = [p,q,v];break;
        case 4: rgb = [t,p,v];break;
        case 5: rgb = [v,p,q];break;
    }

    var r = Math.min(255, Math.round(rgb[0]*256)),
        g = Math.min(255, Math.round(rgb[1]*256)),
        b = Math.min(255, Math.round(rgb[2]*256));

    return [r,g,b];

}	

/**
* Converts RGB to HSV value.
*
* @param {Integer} r Red value, 0-255
* @param {Integer} g Green value, 0-255
* @param {Integer} b Blue value, 0-255
* @returns {Array} The HSV values EG: [h,s,v], [0-360 degrees, 0-100%, 0-100%]
*/
function rgbToHsv(r, g, b) {

    var r = (r / 255),
         g = (g / 255),
  	 b = (b / 255);	

    var min = Math.min(Math.min(r, g), b),
        max = Math.max(Math.max(r, g), b),
        delta = max - min;

    var value = max,
        saturation,
        hue;

    // Hue
    if (max == min) {
        hue = 0;
    } else if (max == r) {
        hue = (60 * ((g-b) / (max-min))) % 360;
    } else if (max == g) {
        hue = 60 * ((b-r) / (max-min)) + 120;
    } else if (max == b) {
        hue = 60 * ((r-g) / (max-min)) + 240;
    }

    if (hue < 0) {
        hue += 360;
    }

    // Saturation
    if (max == 0) {
        saturation = 0;
    } else {
        saturation = 1 - (min/max);
    }

    return [Math.round(hue), Math.round(saturation * 100), Math.round(value * 100)];
}
Aug
03
2008

Javascript Space Invaders

Space Invaders Javascript

Ok, I know this has been done more than once before, but on a paticuarly boring weekend with no money I couldn’t think of a better way to kill the time.

Play the javascript version of Space Invaders here

Making the game was good practice at object oriented javascript, allowing me to play around with things like class inheritance that I hadn’t much experience of in javascript. The game has only been tested in Firefox 2/3 and Safari 3, I will have a go in IE when i get back to work and try and fix accordingly.

After finishing up I was feeling particuarly enthusiastic I went searching for things to do next. I came across Jacob Seidelin’s Nihilogic blog, this site blew me away! There are tons of javascript games on there, mostly using the new canvas tag. A load of interesting topics are covered, such as base64 data encoding, javascript image editing, 3d games and more!

Jul
17
2008

socketBridge: Flash - Javascript Socket Bridge

Update: 5 May 2009
This post has generated a (relatively) large amount of interest so I feel I should point out the ionel is also hosting his improved version of the socketBridge. It has a nicer OO interface and might solve some issues with the javascript callbacks and setTimeouts. Might be worth a peek for all those interested: http://ionelmc.wordpress.com/2008/11/29/flash-socket-bridge-with-haxe/

I’ve been looking at a few flash - javascript socket server bridges recently with the hope of using one to allow me to speak to my Arduino via javascript. I’ve ended up writing my own one here - it’s usually more fun that way, and I can get it to do exactly what I need. However, there’s a couple of good options out there that you might
also want to check out:

SocketJS - Seems to work well and has a nice low file size. The only problem I had with it is that is does not easily allow for object oriented javascript as all of the callbacks are done at the global scope.

jssockets - Nice object oriented interface available here although the function called when the SWF is loaded is still in the global scope. Also this project uses Flex which makes the files size around 120+ KB, a little too large when compared with SocketJS’s ~3KB.

My version is called socketBridge, I think it does most of the things I wanted, mainly allowing for use of object oriented javascript throughout. I also avoided using Flex which kept the filesize nice and low. I’m still not 100% sure about the code quality as this is my first Flash project, prior to this I’d not written any ActionScript at all. To be honest I didn’t even write any here, it was all done using haxe.

Continue reading ‘socketBridge: Flash - Javascript Socket Bridge’ »