Viewport.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. * Value of the initial point of rotation if the viewport is being rotated.
  49. *
  50. * Is set to null when the viewport is not being rotated.
  51. */
  52. this.rotationPoint = null;
  53. }
  54. /**
  55. * Calculate and update the viewport transformation matrix.
  56. *
  57. * Also updates the inverse matrix of the viewport.
  58. */
  59. Viewport.prototype.updateMatrix = function()
  60. {
  61. if(this.matrixNeedsUpdate)
  62. {
  63. this.matrix.compose(this.position.x, this.position.y, this.scale, this.scale, 0, 0, this.rotation);
  64. this.inverseMatrix = this.matrix.getInverse();
  65. //this.matrixNeedsUpdate = false;
  66. }
  67. };
  68. /**
  69. * Center the viewport relative to a object.
  70. *
  71. * The position of the object is used a central point, this method does not consider "box" attributes or other strucures in the object.
  72. *
  73. * @param {Object2D} object Object to be centered on the viewport.
  74. * @param {DOM} canvas Canvas element where the image is drawn.
  75. */
  76. Viewport.prototype.centerObject = function(object, canvas)
  77. {
  78. var position = object.globalMatrix.transformPoint(new Vector2());
  79. position.multiplyScalar(-this.scale);
  80. position.x += canvas.width / 2;
  81. position.y += canvas.height / 2;
  82. this.position.copy(position);
  83. };
  84. export {Viewport};