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?