SwVitaliy

Untitled

May 17th, 2012
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. ;(function(ns)
  3. {
  4.     var color = {};
  5.  
  6.     color.reHexTest = /^\s*#[\da-fA-F]{1,6}\s*$/;
  7.     color.reRgbTest = /^\s*rgb\s*\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)\s*$/i;
  8.     color.reRgbExec = /^\s*rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)\s*$/i;
  9.     color.reHexExec = /^\s*#([\da-fA-F]{1,2})([\da-fA-F]{1,2})?([\da-fA-F]{1,2})?\s*$/;
  10.  
  11.     color.isHex = function(color)
  12.     {
  13.         return this.reHexTest.test(color);
  14.     }
  15.  
  16.     color.isRgb = function(color)
  17.     {
  18.         return this.reRgbTest.test(color);
  19.     }
  20.  
  21.     color.rgbToHex = function(color)
  22.     {
  23.         var rgb;
  24.         if (typeof color === 'object')
  25.         {
  26.             rgb = color[2] | (color[1] << 8) | (color[0] << 16);
  27.         }
  28.         else
  29.         {
  30.             if (this.isHex(color))
  31.             {
  32.                 return color;
  33.             }
  34.  
  35.             if (!this.isRgb(color))
  36.             {
  37.                 return false;
  38.             }
  39.  
  40.             var m = this.reRgbExec.exec(color);
  41.  
  42.             rgb = parseInt(m[3]) | (parseInt(m[2]) << 8) | (parseInt(m[1]) << 16);
  43.         }
  44.  
  45.         rgb = rgb.toString(16);
  46.         rgb = "000000".slice(rgb.length) + rgb;
  47.  
  48.         return '#' + rgb;
  49.     };
  50.  
  51.     color.hexToRgb = function(color, bStr)
  52.     {
  53.         if (this.isRgb(color))
  54.         {
  55.             return color;
  56.         }
  57.  
  58.         if (!this.isHex(color))
  59.         {
  60.             return false;
  61.         }
  62.  
  63.         var m = this.reHexExec.exec(color);
  64.  
  65.         if (!m) { m = ['','0','0','0']; }
  66.         if (!m[1]) m[1] = '0';
  67.         if (!m[2]) m[2] = '0';
  68.         if (!m[3]) m[3] = '0';
  69.  
  70.         var rgb = [ parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16) ]
  71.  
  72.         return (!bStr) ? rgb : "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
  73.     };
  74.  
  75.     ns.textColor = color;
  76.  
  77. })(window)
Advertisement
Add Comment
Please, Sign In to add comment