Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert rgb strings to hex in Javascript

I am using the TweenMax JS library with the ColorPropsPlugin which will tween color values which are specified in many formats, the problem I have is that the result is always in the form of a string:

"rgb(255,255,255)" 

How can that be converted in to a hex number like:

0xffffff 
like image 539
Neil Avatar asked Oct 25 '12 13:10

Neil


People also ask

How to change RGB to HEX in JavaScript?

RGB to Hex. Converting RGB to hex is merely a change of radices. We convert the red, green, and blue values from decimal to hexadecimal using toString(16) . After prepending 0 s to single digits and under, we can concatenate them and # to a single return statement.

How define RGB in Javascript?

CSS rgb() Function The rgb() function define colors using the Red-green-blue (RGB) model. An RGB color value is specified with: rgb(red, green, blue). Each parameter defines the intensity of that color and can be an integer between 0 and 255 or a percentage value (from 0% to 100%).


2 Answers

I would at first cut away the CSS parts:

var a = "rgb(255,255,255)".split("(")[1].split(")")[0]; 

Then split it into separate numbers:

a = a.split(","); 

Convert the single numbers to hex

var b = a.map(function(x){             //For each array element     x = parseInt(x).toString(16);      //Convert to a base16 string     return (x.length==1) ? "0"+x : x;  //Add zero if we get only one character }) 

And glue it back together:

b = "0x"+b.join(""); 
like image 67
Nippey Avatar answered Sep 20 '22 15:09

Nippey


The following is adapted from a Colour class I wrote and use but may be overkill for your needs since it handles percentages and negative numbers.

Demo: http://jsfiddle.net/5ryxx/1/

Code:

function componentFromStr(numStr, percent) {     var num = Math.max(0, parseInt(numStr, 10));     return percent ?         Math.floor(255 * Math.min(100, num) / 100) : Math.min(255, num); }  function rgbToHex(rgb) {     var rgbRegex = /^rgb\(\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*\)$/;     var result, r, g, b, hex = "";     if ( (result = rgbRegex.exec(rgb)) ) {         r = componentFromStr(result[1], result[2]);         g = componentFromStr(result[3], result[4]);         b = componentFromStr(result[5], result[6]);          hex = "0x" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);     }     return hex; } 
like image 31
Tim Down Avatar answered Sep 17 '22 15:09

Tim Down