_rgbToHsl.js.flow 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // @flow
  2. import type {
  3. HslColor, HslaColor, RgbColor, RgbaColor,
  4. } from '../types/color'
  5. function rgbToHsl(color: RgbColor | RgbaColor): HslColor | HslaColor {
  6. // make sure rgb are contained in a set of [0, 255]
  7. const red = color.red / 255
  8. const green = color.green / 255
  9. const blue = color.blue / 255
  10. const max = Math.max(red, green, blue)
  11. const min = Math.min(red, green, blue)
  12. const lightness = (max + min) / 2
  13. if (max === min) {
  14. // achromatic
  15. if (color.alpha !== undefined) {
  16. return {
  17. hue: 0,
  18. saturation: 0,
  19. lightness,
  20. alpha: color.alpha,
  21. }
  22. } else {
  23. return { hue: 0, saturation: 0, lightness }
  24. }
  25. }
  26. let hue
  27. const delta = max - min
  28. const saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min)
  29. switch (max) {
  30. case red:
  31. hue = (green - blue) / delta + (green < blue ? 6 : 0)
  32. break
  33. case green:
  34. hue = (blue - red) / delta + 2
  35. break
  36. default:
  37. // blue case
  38. hue = (red - green) / delta + 4
  39. break
  40. }
  41. hue *= 60
  42. if (color.alpha !== undefined) {
  43. return {
  44. hue,
  45. saturation,
  46. lightness,
  47. alpha: color.alpha,
  48. }
  49. }
  50. return { hue, saturation, lightness }
  51. }
  52. export default rgbToHsl