Posted By

claudiowebdesign on 11/06/11


Tagged

javascript object hex color conversion RGB rgba


Versions (?)

get RGBA values as an object


 / Published in: JavaScript
 

this function gets a parameter like an hex color (es: "#ffffff"), an abbreviated hex color (es: "#fff"), an rgb color (es: "rgb(255,255,255)") or an rgba color (es: "rgba(255,255,255,1)"), and returns an object containing the rgba values, like { red:x, green:y, blue:z, alpha:k }.

  1. function getColorValues( color ){
  2. var values = { red:null, green:null, blue:null, alpha:null };
  3. if( typeof color == 'string' ){
  4. /* hex */
  5. if( color.indexOf('#') === 0 ){
  6. color = color.substr(1)
  7. if( color.length == 3 )
  8. values = {
  9. red: parseInt( color[0]+color[0], 16 ),
  10. green: parseInt( color[1]+color[1], 16 ),
  11. blue: parseInt( color[2]+color[2], 16 ),
  12. alpha: 1
  13. }
  14. else
  15. values = {
  16. red: parseInt( color.substr(0,2), 16 ),
  17. green: parseInt( color.substr(2,2), 16 ),
  18. blue: parseInt( color.substr(4,2), 16 ),
  19. alpha: 1
  20. }
  21. /* rgb */
  22. }else if( color.indexOf('rgb(') === 0 ){
  23. var pars = color.indexOf(',');
  24. values = {
  25. red: parseInt(color.substr(4,pars)),
  26. green: parseInt(color.substr(pars+1,color.indexOf(',',pars))),
  27. blue: parseInt(color.substr(color.indexOf(',',pars+1)+1,color.indexOf(')'))),
  28. alpha: 1
  29. }
  30. /* rgba */
  31. }else if( color.indexOf('rgba(') === 0 ){
  32. var pars = color.indexOf(','),
  33. repars = color.indexOf(',',pars+1);
  34. values = {
  35. red: parseInt(color.substr(5,pars)),
  36. green: parseInt(color.substr(pars+1,repars)),
  37. blue: parseInt(color.substr(color.indexOf(',',pars+1)+1,color.indexOf(',',repars))),
  38. alpha: parseFloat(color.substr(color.indexOf(',',repars+1)+1,color.indexOf(')')))
  39. }
  40. /* verbous */
  41. }else{
  42. var stdCol = { acqua:'#0ff', teal:'#008080', blue:'#00f', navy:'#000080',
  43. yellow:'#ff0', olive:'#808000', lime:'#0f0', green:'#008000',
  44. fuchsia:'#f0f', purple:'#800080', red:'#f00', maroon:'#800000',
  45. white:'#fff', gray:'#808080', silver:'#c0c0c0', black:'#000' };
  46. if( stdCol[color]!=undefined )
  47. values = getColorValues(stdCol[color]);
  48. }
  49. }
  50. return values
  51. }

Report this snippet  

You need to login to post a comment.