color.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Converts various color input formats to an {r:0,g:0,b:0} object.
  3. *
  4. * @param {string} color The string representation of a color
  5. * @example
  6. * colorToRgb('#000');
  7. * @example
  8. * colorToRgb('#000000');
  9. * @example
  10. * colorToRgb('rgb(0,0,0)');
  11. * @example
  12. * colorToRgb('rgba(0,0,0)');
  13. *
  14. * @return {{r: number, g: number, b: number, [a]: number}|null}
  15. */
  16. export const colorToRgb = ( color ) => {
  17. let hex3 = color.match( /^#([0-9a-f]{3})$/i );
  18. if( hex3 && hex3[1] ) {
  19. hex3 = hex3[1];
  20. return {
  21. r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11,
  22. g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11,
  23. b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11
  24. };
  25. }
  26. let hex6 = color.match( /^#([0-9a-f]{6})$/i );
  27. if( hex6 && hex6[1] ) {
  28. hex6 = hex6[1];
  29. return {
  30. r: parseInt( hex6.substr( 0, 2 ), 16 ),
  31. g: parseInt( hex6.substr( 2, 2 ), 16 ),
  32. b: parseInt( hex6.substr( 4, 2 ), 16 )
  33. };
  34. }
  35. let rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i );
  36. if( rgb ) {
  37. return {
  38. r: parseInt( rgb[1], 10 ),
  39. g: parseInt( rgb[2], 10 ),
  40. b: parseInt( rgb[3], 10 )
  41. };
  42. }
  43. let rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i );
  44. if( rgba ) {
  45. return {
  46. r: parseInt( rgba[1], 10 ),
  47. g: parseInt( rgba[2], 10 ),
  48. b: parseInt( rgba[3], 10 ),
  49. a: parseFloat( rgba[4] )
  50. };
  51. }
  52. return null;
  53. }
  54. /**
  55. * Calculates brightness on a scale of 0-255.
  56. *
  57. * @param {string} color See colorToRgb for supported formats.
  58. * @see {@link colorToRgb}
  59. */
  60. export const colorBrightness = ( color ) => {
  61. if( typeof color === 'string' ) color = colorToRgb( color );
  62. if( color ) {
  63. return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000;
  64. }
  65. return null;
  66. }