ColorEditor.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { ColorInput, StringInput, NumberInput, LabelElement, Element } from 'flow';
  2. import { BaseNodeEditor } from '../BaseNodeEditor.js';
  3. import { Color } from 'three';
  4. import { UniformNode } from 'three/nodes';
  5. export class ColorEditor extends BaseNodeEditor {
  6. constructor() {
  7. const v = new Color();
  8. const node = new UniformNode( v );
  9. super( 'Color', node );
  10. const updateFields = ( editing ) => {
  11. const value = node.value;
  12. const hexValue = value.getHex();
  13. const hexString = hexValue.toString( 16 ).toUpperCase().padStart( 6, '0' );
  14. if ( editing !== 'color' ) {
  15. field.setValue( hexValue, false );
  16. }
  17. if ( editing !== 'hex' ) {
  18. hexField.setValue( '#' + hexString, false );
  19. }
  20. if ( editing !== 'rgb' ) {
  21. fieldR.setValue( value.r.toFixed( 3 ), false );
  22. fieldG.setValue( value.g.toFixed( 3 ), false );
  23. fieldB.setValue( value.b.toFixed( 3 ), false );
  24. }
  25. fieldR.setTagColor( `#${hexString.slice( 0, 2 )}0000` );
  26. fieldG.setTagColor( `#00${hexString.slice( 2, 4 )}00` );
  27. fieldB.setTagColor( `#0000${hexString.slice( 4, 6 )}` );
  28. this.invalidate(); // it's important to scriptable nodes ( cpu nodes needs update )
  29. };
  30. const field = new ColorInput( 0xFFFFFF ).onChange( () => {
  31. node.value.setHex( field.getValue() );
  32. updateFields( 'picker' );
  33. } );
  34. const hexField = new StringInput().onChange( () => {
  35. const value = hexField.getValue();
  36. if ( value.indexOf( '#' ) === 0 ) {
  37. const hexStr = value.slice( 1 ).padEnd( 6, '0' );
  38. node.value.setHex( parseInt( hexStr, 16 ) );
  39. updateFields( 'hex' );
  40. }
  41. } );
  42. hexField.addEventListener( 'blur', () => {
  43. updateFields();
  44. } );
  45. const onChangeRGB = () => {
  46. node.value.setRGB( fieldR.getValue(), fieldG.getValue(), fieldB.getValue() );
  47. updateFields( 'rgb' );
  48. };
  49. const fieldR = new NumberInput( 1, 0, 1 ).setTagColor( 'red' ).onChange( onChangeRGB );
  50. const fieldG = new NumberInput( 1, 0, 1 ).setTagColor( 'green' ).onChange( onChangeRGB );
  51. const fieldB = new NumberInput( 1, 0, 1 ).setTagColor( 'blue' ).onChange( onChangeRGB );
  52. this.add( new Element().add( field ).setSerializable( false ) )
  53. .add( new LabelElement( 'Hex' ).add( hexField ).setSerializable( false ) )
  54. .add( new LabelElement( 'RGB' ).add( fieldR ).add( fieldG ).add( fieldB ) );
  55. updateFields();
  56. }
  57. }