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.

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