# 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)]; }

## Michael Richardson

on 6 Feb 2009 at 10:31 pmThank you! Gracious, so many of these conversion scripts didn’t take the 360° nature of the hue into account… This has helped end a couple days of pulling hair.

## my so-called blog » links for 2009-06-09

on 10 Jun 2009 at 2:01 am[...] Javascript Colour Functions » Matt Haynes - Programming & Tech Blog 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 [...]

## bh

on 13 May 2010 at 9:18 amThank you very much for the RGB to HSL converter, works perfectly. You have probably saved me a few hours of work at least.

## Lars

on 28 May 2010 at 7:43 pmThanks for the HSV to RGB conversion!

## simon

on 1 Feb 2011 at 11:34 pmHello Matt im just woundering if you could help me…

im created a colour picker with mark khan tutorial and its all working fine, but i would like to be able to postion the colour slider ect using an external hex value like photoshop, I have had a look and im quite lost really any ideas would be very helpfull many thanks.

## wood restoration

on 9 Apr 2014 at 8:49 amWhat i do not realize is in reality how you are no longer

actually a lot more smartly-appreciated than you may be right

now. You are very intelligent. You already know therefore considerably in the case of this topic, made me for my

part imagine it from so many various angles. Its like women

and men aren’t fascinated unless it is one thing to do with Lady gaga!

Your personal stuffs excellent. All the time take care

of it up!

## freecredit

on 14 Apr 2014 at 5:32 amWhat’s up it’s me, I am also visiting this web page on a regular basis, this site is truly pleasant and the

users are in fact sharing fastidious thoughts.

## floor fitters london

on 14 Apr 2014 at 7:23 amSimply want to say your article is as amazing. The clarity

in your post is just nice and i could assume you’re an expert on

this subject. Well with your permission allow me to grab your RSS feed to keep up to date with forthcoming post.

Thanks a million and please keep up the enjoyable work.