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?

4
  • 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/…. Commented Feb 6, 2016 at 12:07
  • @torazaburo It seems that parse-color or color-convert (which is used by parse-color) do not support alpha value (transparency). Commented Jun 15, 2016 at 15:19
  • @tsh you swapped green and blue. it should read blue = rgba[2]; and green = rgba[1];. Commented Mar 30, 2017 at 14:40
  • @Roberg aha, thank you for pointing out my mistook. edited. Commented Mar 31, 2017 at 1:53

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.