javascript - Parse CSS Color to RGBA values -


i want rgba values <color> css data type values.

the function should accept string describe color, , return object 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, tried codes 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, , chrome. wonder window.getcomputedstyle(x).color return? function always return color in rgb() or rgba() format? specification say?

and, there other way implement parsecolor function?

parsecolor function works creating dummy element , set color it.so can color in rgba() or rgb() (it depends on parameter color is) result in rgba() because

alpha = '3' in rgba ? rgba[3] : 1; 

it means if there no alpha(a) set 1


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -