I tried to convert rgba
to hex color code, but unable to covert opacity value remaining color I able to convert,
Below is my code
var colorcode = "rgba(0, 0, 0, 0.74)";
var finalCode = rgba2hex(colorcode)
function rgba2hex(orig) {
var a, isPercent,
rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
alpha = (rgb && rgb[4] || "").trim(),
hex = rgb ?
(rgb[1] | 1 << 8).toString(16).slice(1) +
(rgb[2] | 1 << 8).toString(16).slice(1) +
(rgb[3] | 1 << 8).toString(16).slice(1) : orig;
if (alpha !== "") { a = alpha; }
else { a = 01; }
hex = hex + a;
return hex;
}
console.log(finalCode)
Here I need alpha value also convert to hex code.
Please suggest how to convert
Output
Expect:000000bd
Since the alpha channel in your rgba() notation is expressed as a 0 ~ 1 value, you need to multiply it by 255 before trying to convert it to its HEX form:
var colorcode = "rgba(0, 0, 0, 0.74)";
var finalCode = rgba2hex(colorcode)
function rgba2hex(orig) {
var a, isPercent,
rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
alpha = (rgb && rgb[4] || "").trim(),
hex = rgb ?
(rgb[1] | 1 << 8).toString(16).slice(1) +
(rgb[2] | 1 << 8).toString(16).slice(1) +
(rgb[3] | 1 << 8).toString(16).slice(1) : orig;
if (alpha !== "") {
a = alpha;
} else {
a = 01;
}
// multiply before convert to HEX
a = ((a * 255) | 1 << 8).toString(16).slice(1)
hex = hex + a;
return hex;
}
function test(colorcode) {
console.log(colorcode, rgba2hex(colorcode));
}
test("rgba(0, 0, 0, 0.74)");
test("rgba(0, 0, 0, 1)");
test("rgba(0, 0, 0, 0)");
test("rgba(0, 255, 0, 0.5)");
But note that this is just one of the rgba notation, and that it will e.g fail with percent based notation.
Note also that all browsers do not support RGBA HEX notation, so you might prefer an other method to convert your values depending on what you want to do with it.
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