utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.97
  5. */
  6. import { hexToRGB } from "../color-picker/utils";
  7. /**
  8. * Convert a string to a valid hex by hashing its contents
  9. * and using the hash as a seed for three distinct color values
  10. *
  11. * @param str
  12. */
  13. export function stringToHex(str) {
  14. let hash = 0;
  15. for (let i = 0; i < str.length; i++) {
  16. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  17. }
  18. let hex = "#";
  19. for (let j = 0; j < 3; j++) {
  20. const value = (hash >> (j * 8)) & 0xff;
  21. hex += ("00" + value.toString(16)).substr(-2);
  22. }
  23. return hex;
  24. }
  25. /**
  26. * Find the hue of a color given the separate RGB color channels
  27. *
  28. * @param rgb
  29. */
  30. export function rgbToHue(rgb) {
  31. let { r, g, b } = rgb;
  32. r /= 255;
  33. g /= 255;
  34. b /= 255;
  35. const max = Math.max(r, g, b);
  36. const min = Math.min(r, g, b);
  37. const delta = max - min;
  38. if (max === min) {
  39. return 0;
  40. }
  41. let hue = (max + min) / 2;
  42. switch (max) {
  43. case r:
  44. hue = (g - b) / delta + (g < b ? 6 : 0);
  45. break;
  46. case g:
  47. hue = (b - r) / delta + 2;
  48. break;
  49. case b:
  50. hue = (r - g) / delta + 4;
  51. break;
  52. }
  53. return Math.round(hue * 60);
  54. }
  55. /**
  56. * For a hex color, find the hue
  57. *
  58. * @param hex {string} - form of "#------"
  59. */
  60. export function hexToHue(hex) {
  61. return rgbToHue(hexToRGB(hex));
  62. }