0
votes

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?

1
window.getComputedStyle(x).color returns what the documents say it returns. See developer.mozilla.org/en-US/docs/Web/API/Window/…. To find other ways to do it, you could google "npm html color". That would lead you to things like this: github.com/substack/parse-color. See also stackoverflow.com/questions/11068240/….user663031
@torazaburo It seems that parse-color or color-convert (which is used by parse-color) do not support alpha value (transparency).tsh
@tsh you swapped green and blue. it should read blue = rgba[2]; and green = rgba[1];.Roberg
@Roberg aha, thank you for pointing out my mistook. edited.tsh

1 Answers

0
votes

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