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.

346 lines
12 KiB

9 years ago
9 years ago
9 years ago
  1. let Hammer = require('../../module/hammer');
  2. let hammerUtil = require('../../hammerUtil');
  3. let util = require('../../util');
  4. /**
  5. * Create the main frame for the Network.
  6. * This function is executed once when a Network object is created. The frame
  7. * contains a canvas, and this canvas contains all objects like the axis and
  8. * nodes.
  9. * @private
  10. */
  11. class Canvas {
  12. constructor(body) {
  13. this.body = body;
  14. this.pixelRatio = 1;
  15. this.resizeTimer = undefined;
  16. this.resizeFunction = this._onResize.bind(this);
  17. this.cameraState = {};
  18. this.options = {};
  19. this.defaultOptions = {
  20. autoResize: true,
  21. height: '100%',
  22. width: '100%'
  23. };
  24. util.extend(this.options, this.defaultOptions);
  25. this.bindEventListeners();
  26. }
  27. bindEventListeners() {
  28. // bind the events
  29. this.body.emitter.once("resize", (obj) => {
  30. if (obj.width !== 0) {
  31. this.body.view.translation.x = obj.width * 0.5;
  32. }
  33. if (obj.height !== 0) {
  34. this.body.view.translation.y = obj.height * 0.5;
  35. }
  36. });
  37. this.body.emitter.on("setSize", this.setSize.bind(this));
  38. this.body.emitter.on("destroy", () => {
  39. this.hammerFrame.destroy();
  40. this.hammer.destroy();
  41. this._cleanUp();
  42. });
  43. }
  44. setOptions(options) {
  45. if (options !== undefined) {
  46. let fields = ['width','height','autoResize'];
  47. util.selectiveDeepExtend(fields,this.options, options);
  48. }
  49. if (this.options.autoResize === true) {
  50. // automatically adapt to a changing size of the browser.
  51. this._cleanUp();
  52. this.resizeTimer = setInterval(() => {
  53. let changed = this.setSize();
  54. if (changed === true) {
  55. this.body.emitter.emit("_requestRedraw");
  56. }
  57. }, 1000);
  58. this.resizeFunction = this._onResize.bind(this);
  59. util.addEventListener(window,'resize',this.resizeFunction);
  60. }
  61. }
  62. _cleanUp() {
  63. // automatically adapt to a changing size of the browser.
  64. if (this.resizeTimer !== undefined) {
  65. clearInterval(this.resizeTimer);
  66. }
  67. util.removeEventListener(window,'resize',this.resizeFunction);
  68. this.resizeFunction = undefined;
  69. }
  70. _onResize() {
  71. this.setSize();
  72. this.body.emitter.emit("_redraw");
  73. }
  74. /**
  75. * Get and store the cameraState
  76. * @private
  77. */
  78. _getCameraState() {
  79. this.cameraState.previousWidth = this.frame.canvas.width;
  80. this.cameraState.scale = this.body.view.scale;
  81. this.cameraState.position = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.width, y: 0.5 * this.frame.canvas.height});
  82. }
  83. /**
  84. * Set the cameraState
  85. * @private
  86. */
  87. _setCameraState() {
  88. if (this.cameraState.scale !== undefined) {
  89. this.body.view.scale = this.body.view.scale * (this.frame.canvas.clientWidth / this.cameraState.previousWidth);
  90. // this comes from the view module.
  91. var viewCenter = this.DOMtoCanvas({
  92. x: 0.5 * this.frame.canvas.clientWidth,
  93. y: 0.5 * this.frame.canvas.clientHeight
  94. });
  95. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  96. x: viewCenter.x - this.cameraState.position.x,
  97. y: viewCenter.y - this.cameraState.position.y
  98. };
  99. this.body.view.translation.x += distanceFromCenter.x * this.body.view.scale;
  100. this.body.view.translation.y += distanceFromCenter.y * this.body.view.scale;
  101. }
  102. }
  103. _prepareValue(value) {
  104. if (typeof value === 'number') {
  105. return value + 'px';
  106. }
  107. else if (typeof value === 'string') {
  108. if (value.indexOf('%') !== -1 || value.indexOf('px') !== -1) {
  109. return value;
  110. }
  111. else if (value.indexOf('%') === -1) {
  112. return value + 'px';
  113. }
  114. }
  115. throw new Error('Could not use the value supplie for width or height:' + value);
  116. }
  117. /**
  118. * Create the HTML
  119. */
  120. _create() {
  121. // remove all elements from the container element.
  122. while (this.body.container.hasChildNodes()) {
  123. this.body.container.removeChild(this.body.container.firstChild);
  124. }
  125. this.frame = document.createElement('div');
  126. this.frame.className = 'vis-network';
  127. this.frame.style.position = 'relative';
  128. this.frame.style.overflow = 'hidden';
  129. this.frame.tabIndex = 900; // tab index is required for keycharm to bind keystrokes to the div instead of the window
  130. //////////////////////////////////////////////////////////////////
  131. this.frame.canvas = document.createElement("canvas");
  132. this.frame.canvas.style.position = 'relative';
  133. this.frame.appendChild(this.frame.canvas);
  134. if (!this.frame.canvas.getContext) {
  135. let noCanvas = document.createElement( 'DIV' );
  136. noCanvas.style.color = 'red';
  137. noCanvas.style.fontWeight = 'bold' ;
  138. noCanvas.style.padding = '10px';
  139. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  140. this.frame.canvas.appendChild(noCanvas);
  141. }
  142. else {
  143. let ctx = this.frame.canvas.getContext("2d");
  144. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  145. ctx.mozBackingStorePixelRatio ||
  146. ctx.msBackingStorePixelRatio ||
  147. ctx.oBackingStorePixelRatio ||
  148. ctx.backingStorePixelRatio || 1);
  149. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  150. }
  151. // add the frame to the container element
  152. this.body.container.appendChild(this.frame);
  153. this.body.view.scale = 1;
  154. this.body.view.translation = {x: 0.5 * this.frame.canvas.clientWidth,y: 0.5 * this.frame.canvas.clientHeight};
  155. this._bindHammer();
  156. }
  157. /**
  158. * This function binds hammer, it can be repeated over and over due to the uniqueness check.
  159. * @private
  160. */
  161. _bindHammer() {
  162. if (this.hammer !== undefined) {
  163. this.hammer.destroy();
  164. }
  165. this.drag = {};
  166. this.pinch = {};
  167. // init hammer
  168. this.hammer = new Hammer(this.frame.canvas);
  169. this.hammer.get('pinch').set({enable: true});
  170. // enable to get better response, todo: test on mobile.
  171. this.hammer.get('pan').set({threshold:5, direction:30}); // 30 is ALL_DIRECTIONS in hammer.
  172. hammerUtil.onTouch(this.hammer, (event) => {this.body.eventListeners.onTouch(event)});
  173. this.hammer.on('tap', (event) => {this.body.eventListeners.onTap(event)});
  174. this.hammer.on('doubletap', (event) => {this.body.eventListeners.onDoubleTap(event)});
  175. this.hammer.on('press', (event) => {this.body.eventListeners.onHold(event)});
  176. this.hammer.on('panstart', (event) => {this.body.eventListeners.onDragStart(event)});
  177. this.hammer.on('panmove', (event) => {this.body.eventListeners.onDrag(event)});
  178. this.hammer.on('panend', (event) => {this.body.eventListeners.onDragEnd(event)});
  179. this.hammer.on('pinch', (event) => {this.body.eventListeners.onPinch(event)});
  180. // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work?
  181. this.frame.canvas.addEventListener('mousewheel', (event) => {this.body.eventListeners.onMouseWheel(event)});
  182. this.frame.canvas.addEventListener('DOMMouseScroll', (event) => {this.body.eventListeners.onMouseWheel(event)});
  183. this.frame.canvas.addEventListener('mousemove', (event) => {this.body.eventListeners.onMouseMove(event)});
  184. this.frame.canvas.addEventListener('contextmenu', (event) => {this.body.eventListeners.onContext(event)});
  185. this.hammerFrame = new Hammer(this.frame);
  186. hammerUtil.onRelease(this.hammerFrame, (event) => {this.body.eventListeners.onRelease(event)});
  187. }
  188. /**
  189. * Set a new size for the network
  190. * @param {string} width Width in pixels or percentage (for example '800px'
  191. * or '50%')
  192. * @param {string} height Height in pixels or percentage (for example '400px'
  193. * or '30%')
  194. */
  195. setSize(width = this.options.width, height = this.options.height) {
  196. this._getCameraState();
  197. width = this._prepareValue(width);
  198. height= this._prepareValue(height);
  199. let emitEvent = false;
  200. let oldWidth = this.frame.canvas.width;
  201. let oldHeight = this.frame.canvas.height;
  202. if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) {
  203. this.frame.style.width = width;
  204. this.frame.style.height = height;
  205. this.frame.canvas.style.width = '100%';
  206. this.frame.canvas.style.height = '100%';
  207. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  208. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  209. this.options.width = width;
  210. this.options.height = height;
  211. emitEvent = true;
  212. }
  213. else {
  214. // this would adapt the width of the canvas to the width from 100% if and only if
  215. // there is a change.
  216. if (this.frame.canvas.width != Math.round(this.frame.canvas.clientWidth * this.pixelRatio)) {
  217. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  218. emitEvent = true;
  219. }
  220. if (this.frame.canvas.height != Math.round(this.frame.canvas.clientHeight * this.pixelRatio)) {
  221. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  222. emitEvent = true;
  223. }
  224. }
  225. if (emitEvent === true) {
  226. this.body.emitter.emit('resize', {
  227. width:Math.round(this.frame.canvas.width / this.pixelRatio),
  228. height:Math.round(this.frame.canvas.height / this.pixelRatio),
  229. oldWidth: Math.round(oldWidth / this.pixelRatio),
  230. oldHeight: Math.round(oldHeight / this.pixelRatio)
  231. });
  232. }
  233. this._setCameraState();
  234. return emitEvent;
  235. };
  236. /**
  237. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  238. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  239. * @param {number} x
  240. * @returns {number}
  241. * @private
  242. */
  243. _XconvertDOMtoCanvas(x) {
  244. return (x - this.body.view.translation.x) / this.body.view.scale;
  245. }
  246. /**
  247. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  248. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  249. * @param {number} x
  250. * @returns {number}
  251. * @private
  252. */
  253. _XconvertCanvasToDOM(x) {
  254. return x * this.body.view.scale + this.body.view.translation.x;
  255. }
  256. /**
  257. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  258. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  259. * @param {number} y
  260. * @returns {number}
  261. * @private
  262. */
  263. _YconvertDOMtoCanvas(y) {
  264. return (y - this.body.view.translation.y) / this.body.view.scale;
  265. }
  266. /**
  267. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  268. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  269. * @param {number} y
  270. * @returns {number}
  271. * @private
  272. */
  273. _YconvertCanvasToDOM(y) {
  274. return y * this.body.view.scale + this.body.view.translation.y;
  275. }
  276. /**
  277. *
  278. * @param {object} pos = {x: number, y: number}
  279. * @returns {{x: number, y: number}}
  280. * @constructor
  281. */
  282. canvasToDOM (pos) {
  283. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  284. }
  285. /**
  286. *
  287. * @param {object} pos = {x: number, y: number}
  288. * @returns {{x: number, y: number}}
  289. * @constructor
  290. */
  291. DOMtoCanvas (pos) {
  292. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  293. }
  294. }
  295. export default Canvas;