vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

329 lines
9.6 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. if (typeof window !== 'undefined') {
  2. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  3. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  4. }
  5. let util = require('../../util');
  6. class CanvasRenderer {
  7. constructor(body, canvas) {
  8. this.body = body;
  9. this.canvas = canvas;
  10. this.redrawRequested = false;
  11. this.renderTimer = undefined;
  12. this.requiresTimeout = true;
  13. this.renderingActive = false;
  14. this.renderRequests = 0;
  15. this.pixelRatio = undefined;
  16. this.allowRedraw = true;
  17. this.dragging = false;
  18. this.options = {};
  19. this.defaultOptions = {
  20. hideEdgesOnDrag: false,
  21. hideNodesOnDrag: false
  22. };
  23. util.extend(this.options, this.defaultOptions);
  24. this._determineBrowserMethod();
  25. this.bindEventListeners();
  26. }
  27. bindEventListeners() {
  28. this.body.emitter.on("dragStart", () => {
  29. this.dragging = true;
  30. });
  31. this.body.emitter.on("dragEnd", () => this.dragging = false);
  32. this.body.emitter.on("_resizeNodes", () => this._resizeNodes());
  33. this.body.emitter.on("_redraw", () => {
  34. if (this.renderingActive === false) {
  35. this._redraw();
  36. }
  37. });
  38. this.body.emitter.on("_blockRedraw", () => {this.allowRedraw = false;});
  39. this.body.emitter.on("_allowRedraw", () => {this.allowRedraw = true; this.redrawRequested = false;});
  40. this.body.emitter.on("_requestRedraw", this._requestRedraw.bind(this));
  41. this.body.emitter.on("_startRendering", () => {
  42. this.renderRequests += 1;
  43. this.renderingActive = true;
  44. this._startRendering();
  45. });
  46. this.body.emitter.on("_stopRendering", () => {
  47. this.renderRequests -= 1;
  48. this.renderingActive = this.renderRequests > 0;
  49. this.renderTimer = undefined;
  50. });
  51. this.body.emitter.on('destroy', () => {
  52. this.renderRequests = 0;
  53. this.allowRedraw = false;
  54. this.renderingActive = false;
  55. if (this.requiresTimeout === true) {
  56. clearTimeout(this.renderTimer);
  57. }
  58. else {
  59. cancelAnimationFrame(this.renderTimer);
  60. }
  61. this.body.emitter.off();
  62. });
  63. }
  64. setOptions(options) {
  65. if (options !== undefined) {
  66. let fields = ['hideEdgesOnDrag','hideNodesOnDrag'];
  67. util.selectiveDeepExtend(fields,this.options, options);
  68. }
  69. }
  70. _startRendering() {
  71. if (this.renderingActive === true) {
  72. if (this.renderTimer === undefined) {
  73. if (this.requiresTimeout === true) {
  74. this.renderTimer = window.setTimeout(this._renderStep.bind(this), this.simulationInterval); // wait this.renderTimeStep milliseconds and perform the animation step function
  75. }
  76. else {
  77. this.renderTimer = window.requestAnimationFrame(this._renderStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function
  78. }
  79. }
  80. }
  81. }
  82. _renderStep() {
  83. if (this.renderingActive === true) {
  84. // reset the renderTimer so a new scheduled animation step can be set
  85. this.renderTimer = undefined;
  86. if (this.requiresTimeout === true) {
  87. // this schedules a new simulation step
  88. this._startRendering();
  89. }
  90. this._redraw();
  91. if (this.requiresTimeout === false) {
  92. // this schedules a new simulation step
  93. this._startRendering();
  94. }
  95. }
  96. }
  97. /**
  98. * Redraw the network with the current data
  99. * chart will be resized too.
  100. */
  101. redraw() {
  102. this.body.emitter.emit('setSize');
  103. this._redraw();
  104. }
  105. /**
  106. * Redraw the network with the current data
  107. * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over.
  108. * @private
  109. */
  110. _requestRedraw() {
  111. if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedraw === true) {
  112. this.redrawRequested = true;
  113. if (this.requiresTimeout === true) {
  114. window.setTimeout(() => {this._redraw(false);}, 0);
  115. }
  116. else {
  117. window.requestAnimationFrame(() => {this._redraw(false);});
  118. }
  119. }
  120. }
  121. _redraw(hidden = false) {
  122. if (this.allowRedraw === true) {
  123. this.body.emitter.emit("initRedraw");
  124. this.redrawRequested = false;
  125. let ctx = this.canvas.frame.canvas.getContext('2d');
  126. // when the container div was hidden, this fixes it back up!
  127. if (this.canvas.frame.canvas.width === 0 || this.canvas.frame.canvas.height === 0) {
  128. this.canvas.setSize();
  129. }
  130. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  131. ctx.mozBackingStorePixelRatio ||
  132. ctx.msBackingStorePixelRatio ||
  133. ctx.oBackingStorePixelRatio ||
  134. ctx.backingStorePixelRatio || 1);
  135. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  136. // clear the canvas
  137. let w = this.canvas.frame.canvas.clientWidth;
  138. let h = this.canvas.frame.canvas.clientHeight;
  139. ctx.clearRect(0, 0, w, h);
  140. // if the div is hidden, we stop the redraw here for performance.
  141. if (this.canvas.frame.clientWidth === 0) {
  142. return;
  143. }
  144. // set scaling and translation
  145. ctx.save();
  146. ctx.translate(this.body.view.translation.x, this.body.view.translation.y);
  147. ctx.scale(this.body.view.scale, this.body.view.scale);
  148. ctx.beginPath();
  149. this.body.emitter.emit("beforeDrawing", ctx);
  150. ctx.closePath();
  151. if (hidden === false) {
  152. if (this.dragging === false || (this.dragging === true && this.options.hideEdgesOnDrag === false)) {
  153. this._drawEdges(ctx);
  154. }
  155. }
  156. if (this.dragging === false || (this.dragging === true && this.options.hideNodesOnDrag === false)) {
  157. this._drawNodes(ctx, hidden);
  158. }
  159. ctx.beginPath();
  160. this.body.emitter.emit("afterDrawing", ctx);
  161. ctx.closePath();
  162. // restore original scaling and translation
  163. ctx.restore();
  164. if (hidden === true) {
  165. ctx.clearRect(0, 0, w, h);
  166. }
  167. }
  168. }
  169. /**
  170. * Redraw all nodes
  171. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  172. * @param {CanvasRenderingContext2D} ctx
  173. * @param {Boolean} [alwaysShow]
  174. * @private
  175. */
  176. _resizeNodes() {
  177. let ctx = this.canvas.frame.canvas.getContext('2d');
  178. if (this.pixelRatio === undefined) {
  179. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  180. ctx.mozBackingStorePixelRatio ||
  181. ctx.msBackingStorePixelRatio ||
  182. ctx.oBackingStorePixelRatio ||
  183. ctx.backingStorePixelRatio || 1);
  184. }
  185. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  186. ctx.save();
  187. ctx.translate(this.body.view.translation.x, this.body.view.translation.y);
  188. ctx.scale(this.body.view.scale, this.body.view.scale);
  189. let nodes = this.body.nodes;
  190. let node;
  191. // resize all nodes
  192. for (let nodeId in nodes) {
  193. if (nodes.hasOwnProperty(nodeId)) {
  194. node = nodes[nodeId];
  195. node.resize(ctx);
  196. node.updateBoundingBox(ctx, node.selected);
  197. }
  198. }
  199. // restore original scaling and translation
  200. ctx.restore();
  201. }
  202. /**
  203. * Redraw all nodes
  204. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  205. * @param {CanvasRenderingContext2D} ctx
  206. * @param {Boolean} [alwaysShow]
  207. * @private
  208. */
  209. _drawNodes(ctx, alwaysShow = false) {
  210. let nodes = this.body.nodes;
  211. let nodeIndices = this.body.nodeIndices;
  212. let node;
  213. let selected = [];
  214. let margin = 20;
  215. let topLeft = this.canvas.DOMtoCanvas({x:-margin,y:-margin});
  216. let bottomRight = this.canvas.DOMtoCanvas({
  217. x: this.canvas.frame.canvas.clientWidth+margin,
  218. y: this.canvas.frame.canvas.clientHeight+margin
  219. });
  220. let viewableArea = {top:topLeft.y,left:topLeft.x,bottom:bottomRight.y,right:bottomRight.x};
  221. // draw unselected nodes;
  222. for (let i = 0; i < nodeIndices.length; i++) {
  223. node = nodes[nodeIndices[i]];
  224. // set selected nodes aside
  225. if (node.isSelected()) {
  226. selected.push(nodeIndices[i]);
  227. }
  228. else {
  229. if (alwaysShow === true) {
  230. node.draw(ctx);
  231. }
  232. else if (node.isBoundingBoxOverlappingWith(viewableArea) === true) {
  233. node.draw(ctx);
  234. }
  235. else {
  236. node.updateBoundingBox(ctx, node.selected);
  237. }
  238. }
  239. }
  240. // draw the selected nodes on top
  241. for (let i = 0; i < selected.length; i++) {
  242. node = nodes[selected[i]];
  243. node.draw(ctx);
  244. }
  245. }
  246. /**
  247. * Redraw all edges
  248. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  249. * @param {CanvasRenderingContext2D} ctx
  250. * @private
  251. */
  252. _drawEdges(ctx) {
  253. let edges = this.body.edges;
  254. let edgeIndices = this.body.edgeIndices;
  255. let edge;
  256. for (let i = 0; i < edgeIndices.length; i++) {
  257. edge = edges[edgeIndices[i]];
  258. if (edge.connected === true) {
  259. edge.draw(ctx);
  260. }
  261. }
  262. }
  263. /**
  264. * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because
  265. * some implementations (safari and IE9) did not support requestAnimationFrame
  266. * @private
  267. */
  268. _determineBrowserMethod() {
  269. if (typeof window !== 'undefined') {
  270. let browserType = navigator.userAgent.toLowerCase();
  271. this.requiresTimeout = false;
  272. if (browserType.indexOf('msie 9.0') != -1) { // IE 9
  273. this.requiresTimeout = true;
  274. }
  275. else if (browserType.indexOf('safari') != -1) { // safari
  276. if (browserType.indexOf('chrome') <= -1) {
  277. this.requiresTimeout = true;
  278. }
  279. }
  280. }
  281. else {
  282. this.requiresTimeout = true;
  283. }
  284. }
  285. }
  286. export default CanvasRenderer;