1

I want get RGBA values from some <color> CSS data type values.

The function should accept a string which describe some color, and return an object with red, green, blue, and, alpha values.

for example:

parseColor('red') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('#f00') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('rgb(255,0,0)') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('hsla(0,100%,50%,0.1)') -> { red: 255, green: 0, blue: 0, alpha: 0.1 }
parseColor('transparent') -> { red: any_is_ok, green: any_is_ok, blue: any_is_ok, alpha: 0 }

So, I tried codes like this:

function parseColor(color) {
  var x = document.createElement('div');
  document.body.appendChild(x);
  var color, rgba;
  var red = 0, green = 0, blue = 0, alpha = 0;
  try {
    x.style = 'color: ' + color + '!important';
    color = window.getComputedStyle(x).color
    rgba = color.match(/rgba?\((.*)\)/)[1].split(',').map(Number);
    red = rgba[0];
    green = rgba[1];
    blue = rgba[2];
    alpha = '3' in rgba ? rgba[3] : 1;
  } catch (e) {
  }
  x.parentNode.removeChild(x);
  return {'red': red, 'green': green, 'blue': blue, 'alpha': alpha};
}

It works in both Firefox, IE, and Chrome. But I wonder what window.getComputedStyle(x).color would return? Will this function always return color in rgb() or rgba() format? What the specification say?

And, is there any other way to implement the parseColor function?

tsh
  • 4,263
  • 5
  • 28
  • 47
  • `window.getComputedStyle(x).color` returns what the documents say it returns. See https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle. To find other ways to do it, you could google "npm html color". That would lead you to things like this: https://github.com/substack/parse-color. See also http://stackoverflow.com/questions/11068240/what-is-the-most-efficient-way-to-parse-a-css-color-in-javascript. –  Feb 06 '16 at 12:07
  • @torazaburo It seems that `parse-color` or `color-convert` (which is used by `parse-color`) do not support alpha value (transparency). – tsh Jun 15 '16 at 15:19
  • @tsh you swapped green and blue. it should read `blue = rgba[2];` and `green = rgba[1];`. – Roberg Mar 30 '17 at 14:40
  • @Roberg aha, thank you for pointing out my mistook. edited. – tsh Mar 31 '17 at 01:53

1 Answers1

0

parseColor function works by creating dummy element and set color to it.So it can get color in rgba() or rgb() (it depends on what parameter color is) but the result will always be in rgba() because

alpha = '3' in rgba ? rgba[3] : 1;

it means if there is no alpha(a) it will set to 1

Elec
  • 1,699
  • 2
  • 13
  • 20