ColorConverter.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { MathUtils } from 'three';
  2. const _hsl = {};
  3. /**
  4. * A utility class with helper functions for color conversion.
  5. *
  6. * @hideconstructor
  7. */
  8. class ColorConverter {
  9. /**
  10. * Sets the given HSV color definition to the given color object.
  11. *
  12. * @param {Color} color - The color to set.
  13. * @param {number} h - The hue.
  14. * @param {number} s - The saturation.
  15. * @param {number} v - The value.
  16. * @return {Color} The update color.
  17. */
  18. static setHSV( color, h, s, v ) {
  19. // https://gist.github.com/xpansive/1337890#file-index-js
  20. h = MathUtils.euclideanModulo( h, 1 );
  21. s = MathUtils.clamp( s, 0, 1 );
  22. v = MathUtils.clamp( v, 0, 1 );
  23. return color.setHSL( h, ( s * v ) / ( ( h = ( 2 - s ) * v ) < 1 ? h : ( 2 - h ) ), h * 0.5 );
  24. }
  25. /**
  26. * Returns a HSV color representation of the given color object.
  27. *
  28. * @param {Color} color - The color to get HSV values from.
  29. * @param {{h:number,s:number,v:number}} target - The target object that is used to store the method's result.
  30. * @return {{h:number,s:number,v:number}} The HSV color.
  31. */
  32. static getHSV( color, target ) {
  33. color.getHSL( _hsl );
  34. // based on https://gist.github.com/xpansive/1337890#file-index-js
  35. _hsl.s *= ( _hsl.l < 0.5 ) ? _hsl.l : ( 1 - _hsl.l );
  36. target.h = _hsl.h;
  37. target.s = 2 * _hsl.s / ( _hsl.l + _hsl.s );
  38. target.v = _hsl.l + _hsl.s;
  39. return target;
  40. }
  41. }
  42. export { ColorConverter };
粤ICP备19079148号