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.

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