I'm parsing a color string returned by getComputedStyle
to get R
, G
, B
, and A
values from it.
So far (in Chrome and Firefox), color values always seem to come back in rgb
or rgba
format which is easy to parse:
const [, r, g, b, a] = str.replace(/\s/g, "").match(/rgba?\((\d+(?:\.\d+)?),(\d+(?:\.\d+)?),(\d+(?:\.\d+)?)(?:,(\d+(?:\.\d+)?))?\)/i);
I cannot, however, find any promise about color format in any of the specs for getComputedStyle
listed on its MDN page.
Is there any guarantee of color format from getComputedStyle
? Or is it entirely up to browser implementation?
I'd prefer not to have to check for HEX and HSLA values (and really whatever else is possible - I'm not entirely sure).
A quick snippet of code for testing color values in your console:
console.log((str => {
const div = document.createElement("div");
div.style.backgroundColor = str;
document.body.append(div);
return getComputedStyle(div).backgroundColor;
})("magenta"));
rgba(0, 0, 0, 0)
– Sordid