color.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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: string) => {
  17. let hex3 = color.match(/^#([0-9a-f]{3})$/i);
  18. if (hex3 && hex3[1]) {
  19. const hex3Value = hex3[1];
  20. return {
  21. r: parseInt(hex3Value.charAt(0), 16) * 0x11,
  22. g: parseInt(hex3Value.charAt(1), 16) * 0x11,
  23. b: parseInt(hex3Value.charAt(2), 16) * 0x11,
  24. };
  25. }
  26. let hex6 = color.match(/^#([0-9a-f]{6})$/i);
  27. if (hex6 && hex6[1]) {
  28. const hex6Value = hex6[1];
  29. return {
  30. r: parseInt(hex6Value.slice(0, 2), 16),
  31. g: parseInt(hex6Value.slice(2, 4), 16),
  32. b: parseInt(hex6Value.slice(4, 6), 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(
  44. /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i
  45. );
  46. if (rgba) {
  47. return {
  48. r: parseInt(rgba[1], 10),
  49. g: parseInt(rgba[2], 10),
  50. b: parseInt(rgba[3], 10),
  51. a: parseFloat(rgba[4]),
  52. };
  53. }
  54. return null;
  55. };
  56. /**
  57. * Calculates brightness on a scale of 0-255.
  58. *
  59. * @param {string} color See colorToRgb for supported formats.
  60. * @see {@link colorToRgb}
  61. */
  62. export const colorBrightness = (color: string | { r: number; g: number; b: number } | null) => {
  63. if (typeof color === 'string') color = colorToRgb(color);
  64. if (color) {
  65. return (color.r * 299 + color.g * 587 + color.b * 114) / 1000;
  66. }
  67. return null;
  68. };