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.

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