Object2D.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. "use strict";
  2. /**
  3. * Base 2D object class, implements all the object positioning and scalling features.
  4. *
  5. * @class
  6. */
  7. function Object2D()
  8. {
  9. /**
  10. * UUID of the object.
  11. */
  12. this.uuid = UUID.generate();
  13. /**
  14. * List of children objects attached to the object.
  15. */
  16. this.children = [];
  17. /**
  18. * Parent object, the object position is affected by its parent position.
  19. */
  20. this.parent = null;
  21. /**
  22. * Position of the object.
  23. */
  24. this.position = new Vector2(0, 0);
  25. /**
  26. * Scale of the object.
  27. */
  28. this.scale = new Vector2(1, 1);
  29. /**
  30. * Rotation of the object relative to its center.
  31. */
  32. this.rotation = 0.0;
  33. /**
  34. * Layer of this object, objects are sorted by layer value.
  35. *
  36. * Lower layer value is draw first.
  37. */
  38. this.layer = 0;
  39. /**
  40. * Local transformation matrix applied to the object.
  41. */
  42. this.matrix = new Matrix();
  43. }
  44. /**
  45. * Traverse the object tree and run a function for all objects.
  46. *
  47. * @param callback Callback function that receives the object as parameter.
  48. */
  49. Object2D.prototype.traverse = function(callback)
  50. {
  51. callback(this);
  52. var children = this.children;
  53. for(var i = 0; i < children.length; i++)
  54. {
  55. children[i].traverse(callback);
  56. }
  57. };
  58. /**
  59. * Attach a children to the object.
  60. *
  61. * @param object Object to attach to this object.
  62. */
  63. Object2D.prototype.add = function(object)
  64. {
  65. object.parent = this;
  66. this.children.push(object);
  67. };
  68. /**
  69. * Remove object from the children list.
  70. *
  71. * @param object Object to be removed.
  72. */
  73. Object2D.prototype.remove = function(object)
  74. {
  75. var index = this.children.indexOf(object);
  76. if(index !== -1)
  77. {
  78. this.children[index].parent = null;
  79. this.children.splice(index, 1)
  80. }
  81. };
  82. /**
  83. * Draw the object into the canvas.
  84. *
  85. * Has to be implemented by underlying classes.
  86. *
  87. * @param context Canvas 2d drawing context.
  88. * @param canvas The canvas DOM element where its being drawn.
  89. */
  90. Object2D.prototype.draw = function(context, canvas)
  91. {
  92. this.matrix.compose(this.position.x, this.position.y, this.scale.x, this.scale.y, this.rotation);
  93. this.matrix.setContextTransform(context);
  94. context.fillRect(-20, -20, 40, 40);
  95. };