Guest User

Untitled

a guest
Sep 24th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. // convert 0..255 R,G,B values to binary string
  2. RGBToBin = function(r,g,b){
  3. var bin = r << 16 | g << 8 | b;
  4. return (function(h){
  5. return new Array(25-h.length).join("0")+h
  6. })(bin.toString(2))
  7. }
  8.  
  9. // convert 0..255 R,G,B values to a hexidecimal color string
  10. RGBToHex = function(r,g,b){
  11. var bin = r << 16 | g << 8 | b;
  12. return (function(h){
  13. return new Array(7-h.length).join("0")+h
  14. })(bin.toString(16).toUpperCase())
  15. }
  16.  
  17. // convert a 24 bit binary color to 0..255 R,G,B
  18. binToRGB = function(bin){
  19. var pbin = parseInt(bin,2);
  20. var r = pbin >> 16;
  21. var g = pbin >> 8 & 0xFF;
  22. var b = pbin & 0xFF;
  23. return [r,g,b];
  24. }
  25.  
  26. // convert a hexidecimal color string to 0..255 R,G,B
  27. hexToRGB = function(hex){
  28. var r = hex >> 16;
  29. var g = hex >> 8 & 0xFF;
  30. var b = hex & 0xFF;
  31. return [r,g,b];
  32. }
  33.  
  34. // simple log function for web/nodejs
  35. log = function(item){
  36. if (document.body){
  37. document.body.innerHTML = document.body.innerHTML+'<pre>'+item+'</pre>';
  38. } else {
  39. console.log(item);
  40. }
  41. }
  42.  
  43. // convert some RGB color values to hex and to binary
  44. new Array(
  45. [000,000,000], // black
  46. [000,255,000], // green
  47. [255,255,255] // white
  48. ).forEach(function(rgb){
  49. var hex = RGBToHex(rgb[0],rgb[1],rgb[2]);
  50. var bin = RGBToBin(rgb[0],rgb[1],rgb[2]);
  51. log('-> RGB: '+rgb+' \n<- HEX: '+hex+' \n<- BIN: '+bin+'\n\n');
  52. });
  53.  
  54. // convert some hexidecimal color values to RGB
  55. new Array(
  56. '000000', // black
  57. '00FF00', // green
  58. 'FFFFFF' // white
  59. ).forEach(function(hex){
  60. var rgb = hexToRGB(parseInt(hex,16));
  61. log('-> HEX: '+hex+' \n<- RGB: '+rgb+'\n\n');
  62. });
  63.  
  64. // convert some 24 bit binary color values to RGB
  65. new Array(
  66. '000000000000000000000000', // black
  67. '000000001111111100000000', // green
  68. '111111111111111111111111' // white
  69. ).forEach(function(bin){
  70. var rgb = binToRGB(bin);
  71. log('-> BIN: '+bin+' \n<- RGB: '+rgb+'\n\n');
  72. });
Add Comment
Please, Sign In to add comment