Posted By

madr on 11/04/10


Tagged

javascript hex generator RGB rgba transluder


Versions (?)

Hex to RGB or RGBA transluder


 / Published in: JavaScript
 

URL: http://madr.se/blog/151

Transform a color given in hex to RGB. An optional opacity argument also enables RBGA.

  1. function hex2rgb(hex, opacity) {
  2. var rgb = hex.replace('#', '').match(/(.{2})/g);
  3.  
  4. var i = 3;
  5. while (i--) {
  6. rgb[i] = parseInt(rgb[i], 16);
  7. }
  8.  
  9. if (typeof opacity == 'undefined') {
  10. return 'rgb(' + rgb.join(', ') + ')';
  11. }
  12.  
  13. return 'rgba(' + rgb.join(', ') + ', ' + opacity + ')';
  14. };

Report this snippet  

You need to login to post a comment.