Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert RGBA to Hex color code using javascript

Tags:

javascript

css

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

like image 208
dhana Avatar asked Apr 23 '18 05:04

dhana


1 Answers

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.

like image 62
Kaiido Avatar answered Sep 27 '22 19:09

Kaiido