My Student partner just asked if i knew any RGB2Hex converters for Javascript, i googled some... until he told me it should take a css RGB : "rgb(255, 17, 17)" -- doh!
var HexLookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
function RGB2Hex(rgb) {
var Hex = "";
while (rgb > 0) {
Hex = HexLookup[rgb % 16] + Hex;
rgb -= (rgb % 16);
rgb /= 16;
}
return Hex;
}
function RGBcss2Hex(str) {
var vals = str.match(/\d+/g);
var hex = "";
for (var i = 0; i < vals.length; i++) {
hex += RGB2Hex(vals[i]);
}
return hex;
}
var rgbText = "rgb(255, 17, 17)";
RGBcss2Hex(rgbText);
the RGBcss2Hex takes a css-rgb string, splits it and use the RGB2Hex converter to convert each "Hexlets"...
finally return the value...
The RGB2Hex also take a combined number, like 16777216 => #FFFFFF
edit:
there are some problems with zeroes not concatting like the rest of numbers :-( ... havent solved it yet.
here is his solution:
function rgb2hex(str) {
var rgb = str.match(/\d+/g);
//generates the hex-digits for a colour.
function hex {
hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8","9", "A", "B", "C", "D", "E", "F");
return isNaN ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x% 16];
}
return "#" + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
}