Guest User

Untitled

a guest
Nov 25th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. /**
  2. * Representation of color in HSL (hue, saturation, luminance) format.
  3. */
  4. interface HslColor {
  5. hue: number;
  6. saturation: number;
  7. luminance: number;
  8. }
  9.  
  10. /**
  11. * Converts hex color string to hsl object
  12. * @param color color string in hex representation
  13. */
  14. function hexToHsl(color: string): HslColor {
  15. const red = parseInt(color.substr(1, 2), 16) / 255;
  16. const green = parseInt(color.substr(3, 2), 16) / 255;
  17. const blue = parseInt(color.substr(5, 2), 16) / 255;
  18.  
  19. const max = Math.max(red, green, blue);
  20. const min = Math.min(red, green, blue);
  21.  
  22. const delta = max - min;
  23.  
  24. let hue;
  25. if (delta === 0) {
  26. hue = 0;
  27. }
  28. else if (max === red) {
  29. hue = 60 * (((green - blue) / delta) % 6);
  30. }
  31. else if (max === green) {
  32. hue = 60 * (((green - blue) / delta) + 2);
  33. }
  34. else if (max === blue) {
  35. hue = 60 * (((green - blue) / delta) + 4);
  36. }
  37.  
  38. const luminance = (max + min) / 2;
  39. const saturation = delta === 0 ? 0 : delta / (1 - Math.abs(2 * luminance - 1));
  40.  
  41. return {hue, saturation, luminance};
  42. }
  43.  
  44. /**
  45. * Convert HSL color object to hex string
  46. * @param color color object in HSL representation
  47. */
  48. function hslToHex(color: HslColor) {
  49. const c = (1 - Math.abs(2 * color.luminance - 1)) * color.saturation;
  50. const x = c * (1 - Math.abs((color.hue / 60) % 2 - 1));
  51. const m = color.luminance - c / 2;
  52.  
  53. let rgbValue: {r: number, g: number, b: number};
  54. if (color.hue >= 0 && color.hue < 60) {
  55. rgbValue = {r: c, g: x, b: 0};
  56. }
  57. else if (color.hue >= 60 && color.hue < 120) {
  58. rgbValue = {r: x, g: c, b: 0};
  59. }
  60. else if (color.hue >= 120 && color.hue < 180) {
  61. rgbValue = {r: 0, g: c, b: x};
  62. }
  63. else if (color.hue >= 180 && color.hue < 240) {
  64. rgbValue = {r: 0, g: x, b: c};
  65. }
  66. else if (color.hue >= 240 && color.hue < 300) {
  67. rgbValue = {r: x, g: 0, b: c};
  68. }
  69. else if (color.hue >= 300 && color.hue < 360) {
  70. rgbValue = {r: c, g: 0, b: x};
  71. }
  72.  
  73. const red = Math.round((rgbValue.r + m) * 255);
  74. const green = Math.round((rgbValue.g + m) * 255);
  75. const blue = Math.round((rgbValue.b + m) * 255);
  76.  
  77. return '#' + red.toString(16) + green.toString(16) + blue.toString(16);
  78. }
Add Comment
Please, Sign In to add comment