utils.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.82
  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. export function stringToHex(str) {
  12. let hash = 0;
  13. for (let i = 0; i < str.length; i++) {
  14. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  15. }
  16. let hex = "#";
  17. for (let j = 0; j < 3; j++) {
  18. const value = (hash >> (j * 8)) & 0xff;
  19. hex += ("00" + value.toString(16)).substr(-2);
  20. }
  21. return hex;
  22. }
  23. /**
  24. * Find the hue of a color given the separate RGB color channels
  25. */
  26. export function rgbToHue(rgb) {
  27. let { r, g, b } = rgb;
  28. r /= 255;
  29. g /= 255;
  30. b /= 255;
  31. const max = Math.max(r, g, b);
  32. const min = Math.min(r, g, b);
  33. const delta = max - min;
  34. if (max === min) {
  35. return 0;
  36. }
  37. let hue = (max + min) / 2;
  38. switch (max) {
  39. case r:
  40. hue = (g - b) / delta + (g < b ? 6 : 0);
  41. break;
  42. case g:
  43. hue = (b - r) / delta + 2;
  44. break;
  45. case b:
  46. hue = (r - g) / delta + 4;
  47. break;
  48. }
  49. return Math.round(hue * 60);
  50. }
  51. /**
  52. * For a hex color, find the hue
  53. * @param hex {string} - form of "#------"
  54. */
  55. export function hexToHue(hex) {
  56. return rgbToHue(hexToRGB(hex));
  57. }