Renderer.js.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: Renderer.js</title>
  6. <script src="scripts/prettify/prettify.js"> </script>
  7. <script src="scripts/prettify/lang-css.js"> </script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  13. </head>
  14. <body>
  15. <div id="main">
  16. <h1 class="page-title">Source: Renderer.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>import {Pointer} from "./input/Pointer.js";
  20. import {ViewportControls} from "./controls/ViewportControls.js";
  21. import {AnimationTimer} from "./utils/AnimationTimer";
  22. import {EventManager} from "./utils/EventManager";
  23. /**
  24. * The renderer is responsible for drawing the objects structure into the canvas element and manage its rendering state.
  25. *
  26. * Object are updated by the renderer before drawing, the renderer sorts the objects by layer, checks for pointer events and draw the objects into the screen.
  27. *
  28. * Input handling is also performed by the renderer (it is also used for the event handling).
  29. *
  30. * @class
  31. * @param {Element} canvas Canvas to render the content to.
  32. * @param {Object} options Renderer canvas options.
  33. */
  34. function Renderer(canvas, options)
  35. {
  36. if(options === undefined)
  37. {
  38. options =
  39. {
  40. alpha: true,
  41. disableContextMenu: true,
  42. imageSmoothingEnabled: true,
  43. imageSmoothingQuality: "low",
  44. globalCompositeOperation: "source-over"
  45. };
  46. }
  47. /**
  48. * Event manager for DOM events created by the renderer.
  49. *
  50. * Created automatically when the renderer is created. Disposed automatically when the renderer is destroyed.
  51. *
  52. * @type {EventManager}
  53. */
  54. this.manager = new EventManager();
  55. if(options.disableContextMenu) {
  56. this.manager.add(canvas, "contextmenu", function(e) {
  57. e.preventDefault();
  58. e.stopPropagation();
  59. });
  60. }
  61. this.manager.create();
  62. /**
  63. * Canvas DOM element, the user needs to manage the canvas state.
  64. *
  65. * The canvas size (width and height) should always match its actual display size (adjusted for the device pixel ratio).
  66. *
  67. * @type {Element}
  68. */
  69. this.canvas = canvas;
  70. /**
  71. * Division where DOM and SVG objects should be placed at. This division should be perfectly aligned whit the canvas element.
  72. *
  73. * If no division is defined the canvas parent element is used by default to place these objects.
  74. *
  75. * The DOM container to be used can be obtained using the getDomContainer() method.
  76. *
  77. * @type {Element}
  78. */
  79. this.container = null;
  80. /**
  81. * Canvas 2D rendering context used to draw content.
  82. *
  83. * The options passed thought the constructor are applied to the context created.
  84. *
  85. * @type {CanvasRenderingContext2D}
  86. */
  87. this.context = this.canvas.getContext("2d", {alpha: options.alpha});
  88. this.context.imageSmoothingEnabled = options.imageSmoothingEnabled;
  89. this.context.imageSmoothingQuality = options.imageSmoothingQuality;
  90. this.context.globalCompositeOperation = options.globalCompositeOperation;
  91. /**
  92. * Pointer input handler object, automatically updated by the renderer.
  93. *
  94. * The pointer is attached to the DOM window and to the canvas provided by the user.
  95. *
  96. * @type {Pointer}
  97. */
  98. this.pointer = new Pointer(window, this.canvas);
  99. /**
  100. * Indicates if the canvas should be automatically cleared before new frame is drawn.
  101. *
  102. * If set to false the user should clear the frame before drawing.
  103. *
  104. * @type {boolean}
  105. */
  106. this.autoClear = true;
  107. }
  108. /**
  109. * Get the DOM container to be used to store DOM and SVG objects.
  110. *
  111. * Can be set using the container attribute, by default the canvas parent element is used.
  112. *
  113. * @returns {Element} DOM element selected for objects.
  114. */
  115. Renderer.prototype.getDomContainer = function()
  116. {
  117. return this.container !== null ? this.container : this.canvas.parentElement;
  118. };
  119. /**
  120. * Creates a infinite render loop to render the group into a viewport each frame.
  121. *
  122. * Automatically creates a viewport controls object, used for the user to control the viewport.
  123. *
  124. * The render loop can be accessed trough the animation timer returned. Should be stopped when no longer necessary to prevent memory/code leaks.
  125. *
  126. * @param {Object2D} group Object to be rendered, alongside with all its children. Object2D can be used as a container to group objects.
  127. * @param {Viewport} viewport Viewport into the scene.
  128. * @param {Function} onUpdate Function called before rendering the frame, can be used for additional logic code. Object logic should be directly written in the update method of objects.
  129. * @return {AnimationTimer} Animation timer created for this render loop. Should be stopped when no longer necessary.
  130. */
  131. Renderer.prototype.createRenderLoop = function(group, viewport, onUpdate)
  132. {
  133. var self = this;
  134. var controls = new ViewportControls(viewport);
  135. var timer = new AnimationTimer(function()
  136. {
  137. if(onUpdate !== undefined)
  138. {
  139. onUpdate();
  140. }
  141. controls.update(self.pointer);
  142. self.update(group, viewport);
  143. });
  144. timer.start();
  145. return timer;
  146. };
  147. /**
  148. * Dispose the renderer object, clears the pointer events attached to the window/canvas.
  149. *
  150. * Should be called if the renderer is no longer in use to prevent code/memory leaks.
  151. */
  152. Renderer.prototype.dispose = function(group, viewport, onUpdate)
  153. {
  154. this.manager.destroy();
  155. this.pointer.dispose();
  156. };
  157. /**
  158. * Renders a object using a user defined viewport into a canvas element.
  159. *
  160. * Before rendering automatically updates the input handlers and calculates the objects/viewport transformation matrices.
  161. *
  162. * The canvas state is saved and restored for each individual object, ensuring that the code of one object does not affect another one.
  163. *
  164. * Should be called at a fixed rate preferably using the requestAnimationFrame() method, its also possible to use the createRenderLoop() method, that automatically creates a infinite render loop.
  165. *
  166. * @param object {Object2D} Object to be updated and drawn into the canvas, the Object2D should be used as a group to store all the other objects to be updated and drawn.
  167. * @param viewport {Viewport} Viewport to be updated (should be the one where the objects will be rendered after).
  168. */
  169. Renderer.prototype.update = function(object, viewport)
  170. {
  171. // Get objects to be rendered
  172. var objects = [];
  173. // Traverse object and get all objects into a list.
  174. object.traverse(function(child)
  175. {
  176. if(child.visible)
  177. {
  178. objects.push(child);
  179. }
  180. });
  181. // Sort objects by layer
  182. objects.sort(function(a, b)
  183. {
  184. if(b.layer === a.layer)
  185. {
  186. return b.level - a.level;
  187. }
  188. return b.layer - a.layer;
  189. });
  190. // Pointer object update
  191. var pointer = this.pointer;
  192. pointer.update();
  193. // Viewport transform matrix
  194. viewport.updateMatrix();
  195. // Project pointer coordinates
  196. var point = pointer.position.clone();
  197. var viewportPoint = viewport.inverseMatrix.transformPoint(point);
  198. // Object pointer events
  199. for(var i = 0; i &lt; objects.length; i++)
  200. {
  201. var child = objects[i];
  202. //Process the object pointer events
  203. if(child.pointerEvents)
  204. {
  205. // Calculate the pointer position in the object coordinates
  206. var localPoint = child.inverseGlobalMatrix.transformPoint(child.ignoreViewport ? point : viewportPoint);
  207. // Check if the pointer pointer is inside
  208. if(child.isInside(localPoint))
  209. {
  210. // Pointer enter
  211. if(!child.pointerInside &amp;&amp; child.onPointerEnter !== null)
  212. {
  213. child.onPointerEnter(pointer, viewport);
  214. }
  215. // Pointer over
  216. if(child.onPointerOver !== null)
  217. {
  218. child.onPointerOver(pointer, viewport);
  219. }
  220. // Double click
  221. if(pointer.buttonDoubleClicked(Pointer.LEFT) &amp;&amp; child.onDoubleClick !== null)
  222. {
  223. child.onDoubleClick(pointer, viewport);
  224. }
  225. // Pointer pressed
  226. if(pointer.buttonPressed(Pointer.LEFT) &amp;&amp; child.onButtonPressed !== null)
  227. {
  228. child.onButtonPressed(pointer, viewport);
  229. }
  230. // Just released
  231. if(pointer.buttonJustReleased(Pointer.LEFT) &amp;&amp; child.onButtonUp !== null)
  232. {
  233. child.onButtonUp(pointer, viewport);
  234. }
  235. // Pointer just pressed
  236. if(pointer.buttonJustPressed(Pointer.LEFT))
  237. {
  238. if(child.onButtonDown !== null)
  239. {
  240. child.onButtonDown(pointer, viewport);
  241. }
  242. // Drag object and break to only start a drag operation on the top element.
  243. if(child.draggable)
  244. {
  245. child.beingDragged = true;
  246. if(child.onPointerDragStart !== null)
  247. {
  248. child.onPointerDragStart(pointer, viewport);
  249. }
  250. break;
  251. }
  252. }
  253. child.pointerInside = true;
  254. }
  255. else if(child.pointerInside)
  256. {
  257. // Pointer leave
  258. if(child.onPointerLeave !== null)
  259. {
  260. child.onPointerLeave(pointer, viewport);
  261. }
  262. child.pointerInside = false;
  263. }
  264. // Stop object drag
  265. if(pointer.buttonJustReleased(Pointer.LEFT))
  266. {
  267. if(child.draggable)
  268. {
  269. // On drag end callback
  270. if(child.beingDragged === true &amp;&amp; child.onPointerDragEnd !== null)
  271. {
  272. child.onPointerDragEnd(pointer, viewport);
  273. }
  274. child.beingDragged = false;
  275. }
  276. }
  277. }
  278. }
  279. // Object drag events and update logic
  280. for(var i = 0; i &lt; objects.length; i++)
  281. {
  282. var child = objects[i];
  283. // Pointer drag event
  284. if(child.beingDragged)
  285. {
  286. if(child.onPointerDrag !== null)
  287. {
  288. var lastPosition = pointer.position.clone();
  289. lastPosition.sub(pointer.delta);
  290. // Get position and last position in world space to calculate world pointer movement
  291. var positionWorld = viewport.inverseMatrix.transformPoint(pointer.position);
  292. var lastWorld = viewport.inverseMatrix.transformPoint(lastPosition);
  293. // Pointer movement delta in world coordinates
  294. var delta = positionWorld.clone();
  295. delta.sub(lastWorld);
  296. child.onPointerDrag(pointer, viewport, delta, positionWorld);
  297. }
  298. }
  299. // On update
  300. if(child.onUpdate !== null)
  301. {
  302. child.onUpdate();
  303. }
  304. }
  305. // Update transformation matrices
  306. object.traverse(function(child)
  307. {
  308. child.updateMatrix();
  309. });
  310. this.context.setTransform(1, 0, 0, 1, 0, 0);
  311. // Clear canvas content
  312. if(this.autoClear)
  313. {
  314. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  315. }
  316. // Render into the canvas
  317. for(var i = objects.length - 1; i >= 0; i--)
  318. {
  319. if(objects[i].isMask)
  320. {
  321. continue;
  322. }
  323. if(objects[i].saveContextState)
  324. {
  325. this.context.save();
  326. }
  327. // Apply all masks
  328. var masks = objects[i].masks;
  329. for(var j = 0; j &lt; masks.length; j++)
  330. {
  331. if(!masks[j].ignoreViewport)
  332. {
  333. viewport.matrix.setContextTransform(this.context);
  334. }
  335. masks[j].transform(this.context, viewport, this.canvas, this);
  336. masks[j].clip(this.context, viewport, this.canvas);
  337. }
  338. // Set the viewport transform
  339. if(!objects[i].ignoreViewport)
  340. {
  341. viewport.matrix.setContextTransform(this.context);
  342. }
  343. else if(masks.length > 0)
  344. {
  345. this.context.setTransform(1, 0, 0, 1, 0, 0);
  346. }
  347. // Apply the object transform to the canvas context
  348. objects[i].transform(this.context, viewport, this.canvas, this);
  349. // Style the canvas context
  350. if(objects[i].style !== null)
  351. {
  352. objects[i].style(this.context, viewport, this.canvas);
  353. }
  354. // Draw content into the canvas.
  355. if(objects[i].draw !== null)
  356. {
  357. objects[i].draw(this.context, viewport, this.canvas);
  358. }
  359. if(objects[i].restoreContextState)
  360. {
  361. this.context.restore();
  362. }
  363. }
  364. };
  365. export {Renderer};
  366. </code></pre>
  367. </article>
  368. </section>
  369. </div>
  370. <nav>
  371. <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="AnimationTimer.html">AnimationTimer</a></li><li><a href="BarGraph.html">BarGraph</a></li><li><a href="BezierCurve.html">BezierCurve</a></li><li><a href="Box.html">Box</a></li><li><a href="Box2.html">Box2</a></li><li><a href="BoxMask.html">BoxMask</a></li><li><a href="Circle.html">Circle</a></li><li><a href="ColorStyle.html">ColorStyle</a></li><li><a href="DOM.html">DOM</a></li><li><a href="EventManager.html">EventManager</a></li><li><a href="FileUtils.html">FileUtils</a></li><li><a href="Gauge.html">Gauge</a></li><li><a href="GradientColorStop.html">GradientColorStop</a></li><li><a href="GradientStyle.html">GradientStyle</a></li><li><a href="Graph.html">Graph</a></li><li><a href="Helpers.html">Helpers</a></li><li><a href="Image.html">Image</a></li><li><a href="Key.html">Key</a></li><li><a href="Line.html">Line</a></li><li><a href="LinearGradientStyle.html">LinearGradientStyle</a></li><li><a href="Mask.html">Mask</a></li><li><a href="Matrix.html">Matrix</a></li><li><a href="MultiLineText.html">MultiLineText</a></li><li><a href="Node.html">Node</a></li><li><a href="NodeConnector.html">NodeConnector</a></li><li><a href="NodeGraph.html">NodeGraph</a></li><li><a href="NodeSocket.html">NodeSocket</a></li><li><a href="Object2D.html">Object2D</a></li><li><a href="Path.html">Path</a></li><li><a href="Pattern.html">Pattern</a></li><li><a href="PatternStyle.html">PatternStyle</a></li><li><a href="PieChart.html">PieChart</a></li><li><a href="Pointer.html">Pointer</a></li><li><a href="QuadraticCurve.html">QuadraticCurve</a></li><li><a href="RadialGradientStyle.html">RadialGradientStyle</a></li><li><a href="Renderer.html">Renderer</a></li><li><a href="RoundedBox.html">RoundedBox</a></li><li><a href="ScatterGraph.html">ScatterGraph</a></li><li><a href="Style.html">Style</a></li><li><a href="Text.html">Text</a></li><li><a href="UUID.html">UUID</a></li><li><a href="Vector2.html">Vector2</a></li><li><a href="Viewport.html">Viewport</a></li><li><a href="ViewportControls.html">ViewportControls</a></li></ul><h3>Global</h3><ul><li><a href="global.html#writeFile">writeFile</a></li></ul>
  372. </nav>
  373. <br class="clear">
  374. <footer>
  375. Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.11</a> on Sat Sep 17 2022 14:24:36 GMT+0100 (Hora de verão da Europa Ocidental)
  376. </footer>
  377. <script> prettyPrint(); </script>
  378. <script src="scripts/linenumber.js"> </script>
  379. </body>
  380. </html>