ColorPickerElement.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { Color3, Color4 } from "babylonjs";
  2. import { PropertyLine } from "../details/PropertyLine";
  3. import { Helpers } from "../helpers/Helpers";
  4. import { Scheduler } from "../scheduler/Scheduler";
  5. import { BasicElement } from "./BasicElement";
  6. /**
  7. * Represents a html div element.
  8. * The div is built when an instance of BasicElement is created.
  9. */
  10. export class ColorPickerElement extends BasicElement {
  11. protected _input: HTMLInputElement;
  12. private pline: PropertyLine;
  13. constructor(color: Color4 | Color3, propertyLine: PropertyLine) {
  14. super();
  15. let scheduler = Scheduler.getInstance();
  16. this._div.className = 'color-element';
  17. this._div.style.backgroundColor = this._toRgba(color);
  18. this.pline = propertyLine;
  19. this._input = Helpers.CreateInput();
  20. this._input.type = 'color';
  21. this._input.style.opacity = "0";
  22. this._input.style.width = '10px';
  23. this._input.style.height = '15px';
  24. this._input.value = color.toHexString();
  25. this._input.addEventListener('input', (e) => {
  26. let color = Color3.FromHexString(this._input.value);
  27. color.r = parseFloat(color.r.toPrecision(2));
  28. color.g = parseFloat(color.g.toPrecision(2));
  29. color.b = parseFloat(color.b.toPrecision(2));
  30. this.pline.validateInput(color);
  31. scheduler.pause = false;
  32. });
  33. this._div.appendChild(this._input);
  34. this._input.addEventListener('click', (e) => {
  35. scheduler.pause = true;
  36. });
  37. }
  38. public update(color?: Color4 | Color3) {
  39. if (color) {
  40. this._div.style.backgroundColor = this._toRgba(color);
  41. this._input.value = color.toHexString();
  42. }
  43. }
  44. private _toRgba(color: Color4 | Color3): string {
  45. if (color) {
  46. let r = (color.r * 255) | 0;
  47. let g = (color.g * 255) | 0;
  48. let b = (color.b * 255) | 0;
  49. let a = 1;
  50. if (color instanceof Color4) {
  51. a = (color as Color4).a;
  52. }
  53. return `rgba(${r}, ${g}, ${b}, ${a})`;
  54. } else {
  55. return '';
  56. }
  57. }
  58. }