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.

365 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(pixelRatio = this.pixelRatio) {
  79. this.cameraState.previousWidth = this.frame.canvas.width / pixelRatio;
  80. this.cameraState.scale = this.body.view.scale;
  81. this.cameraState.position = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.width / pixelRatio, y: 0.5 * this.frame.canvas.height / pixelRatio});
  82. }
  83. /**
  84. * Set the cameraState
  85. * @private
  86. */
  87. _setCameraState() {
  88. if (this.cameraState.scale !== undefined) {
  89. this.body.view.scale = this.cameraState.scale * ((this.frame.canvas.width / this.pixelRatio) / this.cameraState.previousWidth);
  90. // this comes from the view module.
  91. var currentViewCenter = 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: currentViewCenter.x - this.cameraState.position.x,
  97. y: currentViewCenter.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 supplied 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. width = this._prepareValue(width);
  197. height= this._prepareValue(height);
  198. let emitEvent = false;
  199. let oldWidth = this.frame.canvas.width;
  200. let oldHeight = this.frame.canvas.height;
  201. // update the pixelratio
  202. let ctx = this.frame.canvas.getContext("2d");
  203. let previousRation = this.pixelRatio; // we cache this because the camera state storage needs the old value
  204. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  205. ctx.mozBackingStorePixelRatio ||
  206. ctx.msBackingStorePixelRatio ||
  207. ctx.oBackingStorePixelRatio ||
  208. ctx.backingStorePixelRatio || 1);
  209. if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) {
  210. this._getCameraState(previousRation);
  211. this.frame.style.width = width;
  212. this.frame.style.height = height;
  213. this.frame.canvas.style.width = '100%';
  214. this.frame.canvas.style.height = '100%';
  215. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  216. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  217. this.options.width = width;
  218. this.options.height = height;
  219. emitEvent = true;
  220. }
  221. else {
  222. // this would adapt the width of the canvas to the width from 100% if and only if
  223. // there is a change.
  224. // store the camera if there is a change in size.
  225. 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)) {
  226. this._getCameraState(previousRation);
  227. }
  228. if (this.frame.canvas.width != Math.round(this.frame.canvas.clientWidth * this.pixelRatio)) {
  229. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  230. emitEvent = true;
  231. }
  232. if (this.frame.canvas.height != Math.round(this.frame.canvas.clientHeight * this.pixelRatio)) {
  233. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  234. emitEvent = true;
  235. }
  236. }
  237. if (emitEvent === true) {
  238. this.body.emitter.emit('resize', {
  239. width:Math.round(this.frame.canvas.width / this.pixelRatio),
  240. height:Math.round(this.frame.canvas.height / this.pixelRatio),
  241. oldWidth: Math.round(oldWidth / this.pixelRatio),
  242. oldHeight: Math.round(oldHeight / this.pixelRatio)
  243. });
  244. // restore the camera on change.
  245. this._setCameraState();
  246. }
  247. return emitEvent;
  248. };
  249. /**
  250. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  251. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  252. * @param {number} x
  253. * @returns {number}
  254. * @private
  255. */
  256. _XconvertDOMtoCanvas(x) {
  257. return (x - this.body.view.translation.x) / this.body.view.scale;
  258. }
  259. /**
  260. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  261. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  262. * @param {number} x
  263. * @returns {number}
  264. * @private
  265. */
  266. _XconvertCanvasToDOM(x) {
  267. return x * this.body.view.scale + this.body.view.translation.x;
  268. }
  269. /**
  270. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  271. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  272. * @param {number} y
  273. * @returns {number}
  274. * @private
  275. */
  276. _YconvertDOMtoCanvas(y) {
  277. return (y - this.body.view.translation.y) / this.body.view.scale;
  278. }
  279. /**
  280. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  281. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  282. * @param {number} y
  283. * @returns {number}
  284. * @private
  285. */
  286. _YconvertCanvasToDOM(y) {
  287. return y * this.body.view.scale + this.body.view.translation.y;
  288. }
  289. /**
  290. *
  291. * @param {object} pos = {x: number, y: number}
  292. * @returns {{x: number, y: number}}
  293. * @constructor
  294. */
  295. canvasToDOM (pos) {
  296. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  297. }
  298. /**
  299. *
  300. * @param {object} pos = {x: number, y: number}
  301. * @returns {{x: number, y: number}}
  302. * @constructor
  303. */
  304. DOMtoCanvas (pos) {
  305. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  306. }
  307. }
  308. export default Canvas;