ColorConverter.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {
  2. MathUtils
  3. } from '../../../build/three.module.js';
  4. const _hsl = {};
  5. class ColorConverter {
  6. static setHSV( color, h, s, v ) {
  7. // https://gist.github.com/xpansive/1337890#file-index-js
  8. h = MathUtils.euclideanModulo( h, 1 );
  9. s = MathUtils.clamp( s, 0, 1 );
  10. v = MathUtils.clamp( v, 0, 1 );
  11. return color.setHSL( h, ( s * v ) / ( ( h = ( 2 - s ) * v ) < 1 ? h : ( 2 - h ) ), h * 0.5 );
  12. }
  13. static getHSV( color, target ) {
  14. if ( target === undefined ) {
  15. console.warn( 'THREE.ColorConverter: .getHSV() target is now required' );
  16. target = { h: 0, s: 0, l: 0 };
  17. }
  18. color.getHSL( _hsl );
  19. // based on https://gist.github.com/xpansive/1337890#file-index-js
  20. _hsl.s *= ( _hsl.l < 0.5 ) ? _hsl.l : ( 1 - _hsl.l );
  21. target.h = _hsl.h;
  22. target.s = 2 * _hsl.s / ( _hsl.l + _hsl.s );
  23. target.v = _hsl.l + _hsl.s;
  24. return target;
  25. }
  26. // where c, m, y, k is between 0 and 1
  27. static setCMYK( color, c, m, y, k ) {
  28. const r = ( 1 - c ) * ( 1 - k );
  29. const g = ( 1 - m ) * ( 1 - k );
  30. const b = ( 1 - y ) * ( 1 - k );
  31. return color.setRGB( r, g, b );
  32. }
  33. static getCMYK( color, target ) {
  34. if ( target === undefined ) {
  35. console.warn( 'THREE.ColorConverter: .getCMYK() target is now required' );
  36. target = { c: 0, m: 0, y: 0, k: 0 };
  37. }
  38. const r = color.r;
  39. const g = color.g;
  40. const b = color.b;
  41. const k = 1 - Math.max( r, g, b );
  42. const c = ( 1 - r - k ) / ( 1 - k );
  43. const m = ( 1 - g - k ) / ( 1 - k );
  44. const y = ( 1 - b - k ) / ( 1 - k );
  45. target.c = c;
  46. target.m = m;
  47. target.y = y;
  48. target.k = k;
  49. return target;
  50. }
  51. }
  52. export { ColorConverter };