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
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.
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%).
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("");
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With