I am trying to find a method which can convert RGB or RGBA string to hex format. i found solution but not in one method like method 1 => rgbToHex and for RGBA rgbaToHex i want to combine them so it can return hex value of both RGB and RGBA
RGB method:
// convert RGB color data to hex
function rgb2hex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
RGBA method:
function rgba2hex(r, g, b, a) {
if (r > 255 || g > 255 || b > 255 || a > 255)
throw "Invalid color component";
return (256 + r).toString(16).substr(1) +((1 << 24) + (g << 16) | (b << 8) | a).toString(16).substr(1);
}
What i want:
//takes both RGB and RGBA and convert to HEX like #000000
// input will be string like this => rgb(0,0,0) or rgba(255,255,255, 0.5)
function anyToHex() {
return; // hex value
}
i created my solution which can take take any string rgb or rgba and then return a HEX value Here is my soution:
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function anytoHEX(string) {
rgb = string.substring(4, string.length-1).replace(/ /g, '').split(',');
R = rgb[0].replace("(", "");
G = rgb[1];
B = rgb[2];
return "#" + componentToHex(R) + componentToHex(G) + componentToHex(B);
}
console.log(anytoHEX('rgba(0,0,0,0)'));