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.

406 lines
13 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._setPixelRatio(ctx);
  169. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  170. }
  171. // add the frame to the container element
  172. this.body.container.appendChild(this.frame);
  173. this.body.view.scale = 1;
  174. this.body.view.translation = {x: 0.5 * this.frame.canvas.clientWidth,y: 0.5 * this.frame.canvas.clientHeight};
  175. this._bindHammer();
  176. }
  177. /**
  178. * This function binds hammer, it can be repeated over and over due to the uniqueness check.
  179. * @private
  180. */
  181. _bindHammer() {
  182. if (this.hammer !== undefined) {
  183. this.hammer.destroy();
  184. }
  185. this.drag = {};
  186. this.pinch = {};
  187. // init hammer
  188. this.hammer = new Hammer(this.frame.canvas);
  189. this.hammer.get('pinch').set({enable: true});
  190. // enable to get better response, todo: test on mobile.
  191. this.hammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_ALL});
  192. hammerUtil.onTouch(this.hammer, (event) => {this.body.eventListeners.onTouch(event)});
  193. this.hammer.on('tap', (event) => {this.body.eventListeners.onTap(event)});
  194. this.hammer.on('doubletap', (event) => {this.body.eventListeners.onDoubleTap(event)});
  195. this.hammer.on('press', (event) => {this.body.eventListeners.onHold(event)});
  196. this.hammer.on('panstart', (event) => {this.body.eventListeners.onDragStart(event)});
  197. this.hammer.on('panmove', (event) => {this.body.eventListeners.onDrag(event)});
  198. this.hammer.on('panend', (event) => {this.body.eventListeners.onDragEnd(event)});
  199. this.hammer.on('pinch', (event) => {this.body.eventListeners.onPinch(event)});
  200. // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work?
  201. this.frame.canvas.addEventListener('mousewheel', (event) => {this.body.eventListeners.onMouseWheel(event)});
  202. this.frame.canvas.addEventListener('DOMMouseScroll', (event) => {this.body.eventListeners.onMouseWheel(event)});
  203. this.frame.canvas.addEventListener('mousemove', (event) => {this.body.eventListeners.onMouseMove(event)});
  204. this.frame.canvas.addEventListener('contextmenu', (event) => {this.body.eventListeners.onContext(event)});
  205. this.hammerFrame = new Hammer(this.frame);
  206. hammerUtil.onRelease(this.hammerFrame, (event) => {this.body.eventListeners.onRelease(event)});
  207. }
  208. /**
  209. * Set a new size for the network
  210. * @param {string} width Width in pixels or percentage (for example '800px'
  211. * or '50%')
  212. * @param {string} height Height in pixels or percentage (for example '400px'
  213. * or '30%')
  214. */
  215. setSize(width = this.options.width, height = this.options.height) {
  216. width = this._prepareValue(width);
  217. height= this._prepareValue(height);
  218. let emitEvent = false;
  219. let oldWidth = this.frame.canvas.width;
  220. let oldHeight = this.frame.canvas.height;
  221. // update the pixel ratio
  222. let ctx = this.frame.canvas.getContext("2d");
  223. let previousRatio = this.pixelRatio; // we cache this because the camera state storage needs the old value
  224. this._setPixelRatio(ctx);
  225. if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) {
  226. this._getCameraState(previousRatio);
  227. this.frame.style.width = width;
  228. this.frame.style.height = height;
  229. this.frame.canvas.style.width = '100%';
  230. this.frame.canvas.style.height = '100%';
  231. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  232. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  233. this.options.width = width;
  234. this.options.height = height;
  235. this.canvasViewCenter = {
  236. x: 0.5 * this.frame.clientWidth,
  237. y: 0.5 * this.frame.clientHeight
  238. };
  239. emitEvent = true;
  240. }
  241. else {
  242. // this would adapt the width of the canvas to the width from 100% if and only if
  243. // there is a change.
  244. let newWidth = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  245. let newHeight = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  246. // store the camera if there is a change in size.
  247. if (this.frame.canvas.width !== newWidth || this.frame.canvas.height !== newHeight) {
  248. this._getCameraState(previousRatio);
  249. }
  250. if (this.frame.canvas.width !== newWidth) {
  251. this.frame.canvas.width = newWidth;
  252. emitEvent = true;
  253. }
  254. if (this.frame.canvas.height !== newHeight) {
  255. this.frame.canvas.height = newHeight;
  256. emitEvent = true;
  257. }
  258. }
  259. if (emitEvent === true) {
  260. this.body.emitter.emit('resize', {
  261. width : Math.round(this.frame.canvas.width / this.pixelRatio),
  262. height : Math.round(this.frame.canvas.height / this.pixelRatio),
  263. oldWidth : Math.round(oldWidth / this.pixelRatio),
  264. oldHeight: Math.round(oldHeight / this.pixelRatio)
  265. });
  266. // restore the camera on change.
  267. this._setCameraState();
  268. }
  269. // set initialized so the get and set camera will work from now on.
  270. this.initialized = true;
  271. return emitEvent;
  272. };
  273. /**
  274. * @private
  275. */
  276. _setPixelRatio(ctx) {
  277. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  278. ctx.mozBackingStorePixelRatio ||
  279. ctx.msBackingStorePixelRatio ||
  280. ctx.oBackingStorePixelRatio ||
  281. ctx.backingStorePixelRatio || 1);
  282. }
  283. /**
  284. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  285. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  286. * @param {number} x
  287. * @returns {number}
  288. * @private
  289. */
  290. _XconvertDOMtoCanvas(x) {
  291. return (x - this.body.view.translation.x) / this.body.view.scale;
  292. }
  293. /**
  294. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  295. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  296. * @param {number} x
  297. * @returns {number}
  298. * @private
  299. */
  300. _XconvertCanvasToDOM(x) {
  301. return x * this.body.view.scale + this.body.view.translation.x;
  302. }
  303. /**
  304. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  305. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  306. * @param {number} y
  307. * @returns {number}
  308. * @private
  309. */
  310. _YconvertDOMtoCanvas(y) {
  311. return (y - this.body.view.translation.y) / this.body.view.scale;
  312. }
  313. /**
  314. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  315. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  316. * @param {number} y
  317. * @returns {number}
  318. * @private
  319. */
  320. _YconvertCanvasToDOM(y) {
  321. return y * this.body.view.scale + this.body.view.translation.y;
  322. }
  323. /**
  324. *
  325. * @param {object} pos = {x: number, y: number}
  326. * @returns {{x: number, y: number}}
  327. * @constructor
  328. */
  329. canvasToDOM (pos) {
  330. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  331. }
  332. /**
  333. *
  334. * @param {object} pos = {x: number, y: number}
  335. * @returns {{x: number, y: number}}
  336. * @constructor
  337. */
  338. DOMtoCanvas (pos) {
  339. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  340. }
  341. }
  342. export default Canvas;