Site Moved

This site has been moved to a new location - Bin-Blog. All new post will appear at the new location.


Javascript Functions for converting Hex colour to RBG Values

I recently needed to create a fade effect for some text for the new version of Sudoku. In the process of creating the effect, I needed to convert three Red,Blue and Green values to a Hex code - the format of colour used in HTML. For example, if the values 255,255,255 is given, the hex code #FFFFFF must be returned.

The code for the two hex convertion functions are given here. As for the fade effect function, well that will be made available in a later post. There are the two functions...

This function will accept a hex colour value(like #0FCAF8) and convert it to an array with three elements. The first element of the array will be the value of red, the second will be blue and the third one will be green. For example...
hex2num("#0FCAF8") will return the value 15,202,248.
This function will take an array with three elements and return a hex value created from it. For example...
hex2num(new Array(15,202,248)) will return the value #0FCAF8.


//Convert a hex value to its decimal value - the inputed hex must be in the
// format of a hex triplet - the kind we use for HTML colours. The function
// will return an array with three values.
function hex2num(hex) {
 if(hex.charAt(0) == "#") hex = hex.slice(1); //Remove the '#' char - if there is one.
 hex = hex.toUpperCase();
 var hex_alphabets = "0123456789ABCDEF";
 var value = new Array(3);
 var k = 0;
 var int1,int2;
 for(var i=0;i<6;i+=2) {
  int1 = hex_alphabets.indexOf(hex.charAt(i));
  int2 = hex_alphabets.indexOf(hex.charAt(i+1)); 
  value[k] = (int1 * 16) + int2;
//Give a array with three values as the argument and the function will return
// the corresponding hex triplet.
function num2hex(triplet) {
 var hex_alphabets = "0123456789ABCDEF";
 var hex = "#";
 var int1,int2;
 for(var i=0;i<3;i++) {
  int1 = triplet[i] / 16;
  int2 = triplet[i] % 16;

  hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2); 

Filed Under...

1 Comment:

Anonymous said...

Ёбаные индусы. Метод Number.toString(radix) им неведом.