ViewportControls.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. "use strict";
  2. import {Viewport} from "../Viewport.js";
  3. import {Pointer} from "../input/Pointer.js";
  4. /**
  5. * Viewport controls are used to allow the user to control the viewport.
  6. *
  7. * @class
  8. * @param {Viewport} viewport
  9. */
  10. function ViewportControls(viewport)
  11. {
  12. /**
  13. * Viewport being controlled by this object.
  14. */
  15. this.viewport = viewport;
  16. /**
  17. * Button used to drag and viewport around.
  18. */
  19. this.dragButton = Pointer.LEFT;
  20. /**
  21. * If true allows the viewport to be rotated.
  22. */
  23. this.allowRotation = false;
  24. /**
  25. * Flag to indicate if the viewport should move when scalling.
  26. *
  27. * For some application its easier to focus the target if the viewport moves to the pointer location while scalling.
  28. */
  29. this.moveOnScale = true;
  30. /**
  31. * Value of the initial point of rotation if the viewport is being rotated.
  32. *
  33. * Is set to null when the viewport is not being rotated.
  34. */
  35. this.rotationPoint = null;
  36. }
  37. /**
  38. * Update the viewport controls using the pointer object.
  39. */
  40. ViewportControls.prototype.update = function(pointer)
  41. {
  42. if(pointer.wheel !== 0)
  43. {
  44. this.viewport.scale -= pointer.wheel * 1e-3 * this.viewport.scale;
  45. if(this.moveOnScale)
  46. {
  47. var speed = pointer.wheel;
  48. var halfWidth = pointer.canvas.width / 2;
  49. var halfWeight = pointer.canvas.height / 2;
  50. this.viewport.position.x += ((pointer.position.x - halfWidth) / halfWidth) * speed;
  51. this.viewport.position.y += ((pointer.position.y - halfWeight) / halfWeight) * speed;
  52. }
  53. }
  54. if(this.allowRotation && pointer.buttonPressed(Pointer.RIGHT) && pointer.buttonPressed(Pointer.LEFT))
  55. {
  56. if(this.rotationPoint === null)
  57. {
  58. this.rotationPoint = pointer.position.clone();
  59. }
  60. else
  61. {
  62. //TODO <USE ROTATION POINT>
  63. this.viewport.rotation += pointer.delta.angle() * 1e-3;
  64. }
  65. }
  66. else
  67. {
  68. this.rotationPoint = null;
  69. if(pointer.buttonPressed(this.dragButton))
  70. {
  71. this.viewport.position.x += pointer.delta.x;
  72. this.viewport.position.y += pointer.delta.y;
  73. }
  74. }
  75. };