Given a string of a valid CSS color value:
Need to get an array of numbers of t
Trying @Niet_the_Dark_Absol's answer with this beautiful getComputedStyle hack, I've been unable to make it work until appending to the DOM the created element (Chrome 69 and Firefox 75).
As I also wanted to be able to handle the alpha channel value (transparency), I modified the Regex and returned result.
Here is my function if it can be of any help for anyone:
function colorToRgbParser(cssColor) {
const div = document.createElement('div');
div.id = 'for-computed-style';
div.style.color = cssColor;
// appending the created element to the DOM
document.querySelector('body').appendChild(div);
const match = getComputedStyle(div).color.match(/^rgba?\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d\.\d)\s*)?\)$/i);
// removing element from the DOM
document.querySelector('#for-computed-style').remove();
if (match) {
// match[0] is regex complete match (e.g. "rgb(0,0,0)"), not a regex capturing group
let parsedColor = {
r: match[1],
g: match[2],
b: match[3]
};
if (match[4]) { // if alpha channel is present
parsedColor.a = match[4];
}
return parsedColor;
} else {
throw new Error(`Color ${cssColor} could not be parsed.`);
}
}