Viewport.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. "use strict";
  2. import {Vector2} from "./math/Vector2.js";
  3. import {Matrix} from "./math/Matrix.js";
  4. import {UUID} from "./math/UUID.js";
  5. import {Pointer} from "./input/Pointer.js";
  6. /**
  7. * Used to indicate how the user views the content inside of the canvas.
  8. *
  9. * @class
  10. */
  11. function Viewport()
  12. {
  13. /**
  14. * UUID of the object.
  15. */
  16. this.uuid = UUID.generate();
  17. /**
  18. * Position of the object.
  19. */
  20. this.position = new Vector2(0, 0);
  21. /**
  22. * Scale of the object.
  23. */
  24. this.scale = 1.0
  25. /**
  26. * Rotation of the object relative to its center.
  27. */
  28. this.rotation = 0.0;
  29. /**
  30. * Local transformation matrix applied to the object.
  31. */
  32. this.matrix = new Matrix();
  33. /**
  34. * Inverse of the local transformation matrix.
  35. */
  36. this.inverseMatrix = new Matrix();
  37. /**
  38. * If true the matrix is updated before rendering the object.
  39. */
  40. this.matrixNeedsUpdate = true;
  41. /**
  42. * Flag to indicate if the viewport should move when scalling.
  43. *
  44. * For some application its easier to focus the target if the viewport moves to the pointer location while scalling.
  45. */
  46. this.moveOnScale = true;
  47. }
  48. /**
  49. * Update the viewport controls using the pointer object.
  50. */
  51. Viewport.prototype.updateControls = function(pointer)
  52. {
  53. if(pointer.wheel !== 0)
  54. {
  55. this.scale -= pointer.wheel * 1e-3 * this.scale;
  56. if(this.moveOnScale)
  57. {
  58. var speed = pointer.wheel / this.scale;
  59. var halfWidth = pointer.canvas.width / 2;
  60. var halfWeight = pointer.canvas.height / 2;
  61. this.position.x += ((pointer.position.x - halfWidth) / halfWidth) * speed;
  62. this.position.y += ((pointer.position.y - halfWeight) / halfWeight) * speed;
  63. }
  64. }
  65. if(pointer.buttonPressed(Pointer.RIGHT))
  66. {
  67. this.position.x += pointer.delta.x;
  68. this.position.y += pointer.delta.y;
  69. }
  70. };
  71. /**
  72. * Calculate and update the viewport transformation matrix.
  73. */
  74. Viewport.prototype.updateMatrix = function()
  75. {
  76. if(this.matrixNeedsUpdate)
  77. {
  78. this.matrix.compose(this.position.x, this.position.y, this.scale, this.scale, this.rotation);
  79. this.inverseMatrix = this.matrix.getInverse();
  80. //this.matrixNeedsUpdate = false;
  81. }
  82. };
  83. export {Viewport};