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.

1347 lines
40 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var util = require('../util');
  2. var Node = require('./Node');
  3. /**
  4. * @class Edge
  5. *
  6. * A edge connects two nodes
  7. * @param {Object} properties Object with properties. Must contain
  8. * At least properties from and to.
  9. * Available properties: from (number),
  10. * to (number), label (string, color (string),
  11. * width (number), style (string),
  12. * length (number), title (string)
  13. * @param {Network} network A Network object, used to find and edge to
  14. * nodes.
  15. * @param {Object} constants An object with default values for
  16. * example for the color
  17. */
  18. function Edge (properties, network, networkConstants) {
  19. if (!network) {
  20. throw "No network provided";
  21. }
  22. var fields = ['edges','physics'];
  23. var constants = util.selectiveBridgeObject(fields,networkConstants);
  24. this.options = constants.edges;
  25. this.physics = constants.physics;
  26. this.options['smoothCurves'] = networkConstants['smoothCurves'];
  27. this.network = network;
  28. // initialize variables
  29. this.id = undefined;
  30. this.fromId = undefined;
  31. this.toId = undefined;
  32. this.title = undefined;
  33. this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
  34. this.value = undefined;
  35. this.selected = false;
  36. this.hover = false;
  37. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  38. this.dirtyLabel = true;
  39. this.from = null; // a node
  40. this.to = null; // a node
  41. this.via = null; // a temp node
  42. this.fromBackup = null; // used to clean up after reconnect
  43. this.toBackup = null;; // used to clean up after reconnect
  44. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  45. // by storing the original information we can revert to the original connection when the cluser is opened.
  46. this.originalFromId = [];
  47. this.originalToId = [];
  48. this.connected = false;
  49. this.widthFixed = false;
  50. this.lengthFixed = false;
  51. this.setProperties(properties);
  52. this.controlNodesEnabled = false;
  53. this.controlNodes = {from:null, to:null, positions:{}};
  54. this.connectedNode = null;
  55. }
  56. /**
  57. * Set or overwrite properties for the edge
  58. * @param {Object} properties an object with properties
  59. * @param {Object} constants and object with default, global properties
  60. */
  61. Edge.prototype.setProperties = function(properties) {
  62. if (!properties) {
  63. return;
  64. }
  65. var fields = ['style','fontSize','fontFace','fontColor','fontFill','fontStrokeWidth','fontStrokeColor','width',
  66. 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor','labelAlignment'
  67. ];
  68. util.selectiveDeepExtend(fields, this.options, properties);
  69. if (properties.from !== undefined) {this.fromId = properties.from;}
  70. if (properties.to !== undefined) {this.toId = properties.to;}
  71. if (properties.id !== undefined) {this.id = properties.id;}
  72. if (properties.label !== undefined) {this.label = properties.label; this.dirtyLabel = true;}
  73. if (properties.title !== undefined) {this.title = properties.title;}
  74. if (properties.value !== undefined) {this.value = properties.value;}
  75. if (properties.length !== undefined) {this.physics.springLength = properties.length;}
  76. if (properties.color !== undefined) {
  77. this.options.inheritColor = false;
  78. if (util.isString(properties.color)) {
  79. this.options.color.color = properties.color;
  80. this.options.color.highlight = properties.color;
  81. }
  82. else {
  83. if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
  84. if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
  85. if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
  86. }
  87. }
  88. // A node is connected when it has a from and to node.
  89. this.connect();
  90. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  91. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  92. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  93. // set draw method based on style
  94. switch (this.options.style) {
  95. case 'line': this.draw = this._drawLine; break;
  96. case 'arrow': this.draw = this._drawArrow; break;
  97. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  98. case 'dash-line': this.draw = this._drawDashLine; break;
  99. default: this.draw = this._drawLine; break;
  100. }
  101. };
  102. /**
  103. * Connect an edge to its nodes
  104. */
  105. Edge.prototype.connect = function () {
  106. this.disconnect();
  107. this.from = this.network.nodes[this.fromId] || null;
  108. this.to = this.network.nodes[this.toId] || null;
  109. this.connected = (this.from && this.to);
  110. if (this.connected) {
  111. this.from.attachEdge(this);
  112. this.to.attachEdge(this);
  113. }
  114. else {
  115. if (this.from) {
  116. this.from.detachEdge(this);
  117. }
  118. if (this.to) {
  119. this.to.detachEdge(this);
  120. }
  121. }
  122. };
  123. /**
  124. * Disconnect an edge from its nodes
  125. */
  126. Edge.prototype.disconnect = function () {
  127. if (this.from) {
  128. this.from.detachEdge(this);
  129. this.from = null;
  130. }
  131. if (this.to) {
  132. this.to.detachEdge(this);
  133. this.to = null;
  134. }
  135. this.connected = false;
  136. };
  137. /**
  138. * get the title of this edge.
  139. * @return {string} title The title of the edge, or undefined when no title
  140. * has been set.
  141. */
  142. Edge.prototype.getTitle = function() {
  143. return typeof this.title === "function" ? this.title() : this.title;
  144. };
  145. /**
  146. * Retrieve the value of the edge. Can be undefined
  147. * @return {Number} value
  148. */
  149. Edge.prototype.getValue = function() {
  150. return this.value;
  151. };
  152. /**
  153. * Adjust the value range of the edge. The edge will adjust it's width
  154. * based on its value.
  155. * @param {Number} min
  156. * @param {Number} max
  157. */
  158. Edge.prototype.setValueRange = function(min, max) {
  159. if (!this.widthFixed && this.value !== undefined) {
  160. var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
  161. this.options.width= (this.value - min) * scale + this.options.widthMin;
  162. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  163. }
  164. };
  165. /**
  166. * Redraw a edge
  167. * Draw this edge in the given canvas
  168. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  169. * @param {CanvasRenderingContext2D} ctx
  170. */
  171. Edge.prototype.draw = function(ctx) {
  172. throw "Method draw not initialized in edge";
  173. };
  174. /**
  175. * Check if this object is overlapping with the provided object
  176. * @param {Object} obj an object with parameters left, top
  177. * @return {boolean} True if location is located on the edge
  178. */
  179. Edge.prototype.isOverlappingWith = function(obj) {
  180. if (this.connected) {
  181. var distMax = 10;
  182. var xFrom = this.from.x;
  183. var yFrom = this.from.y;
  184. var xTo = this.to.x;
  185. var yTo = this.to.y;
  186. var xObj = obj.left;
  187. var yObj = obj.top;
  188. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  189. return (dist < distMax);
  190. }
  191. else {
  192. return false
  193. }
  194. };
  195. Edge.prototype._getColor = function() {
  196. var colorObj = this.options.color;
  197. if (this.options.inheritColor == "to") {
  198. colorObj = {
  199. highlight: this.to.options.color.highlight.border,
  200. hover: this.to.options.color.hover.border,
  201. color: this.to.options.color.border
  202. };
  203. }
  204. else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
  205. colorObj = {
  206. highlight: this.from.options.color.highlight.border,
  207. hover: this.from.options.color.hover.border,
  208. color: this.from.options.color.border
  209. };
  210. }
  211. if (this.selected == true) {return colorObj.highlight;}
  212. else if (this.hover == true) {return colorObj.hover;}
  213. else {return colorObj.color;}
  214. };
  215. /**
  216. * Redraw a edge as a line
  217. * Draw this edge in the given canvas
  218. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  219. * @param {CanvasRenderingContext2D} ctx
  220. * @private
  221. */
  222. Edge.prototype._drawLine = function(ctx) {
  223. // set style
  224. ctx.strokeStyle = this._getColor();
  225. ctx.lineWidth = this._getLineWidth();
  226. if (this.from != this.to) {
  227. // draw line
  228. var via = this._line(ctx);
  229. // draw label
  230. var point;
  231. if (this.label) {
  232. if (this.options.smoothCurves.enabled == true && via != null) {
  233. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  234. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  235. point = {x:midpointX, y:midpointY};
  236. }
  237. else {
  238. point = this._pointOnLine(0.5);
  239. }
  240. this._label(ctx, this.label, point.x, point.y);
  241. }
  242. }
  243. else {
  244. var x, y;
  245. var radius = this.physics.springLength / 4;
  246. var node = this.from;
  247. if (!node.width) {
  248. node.resize(ctx);
  249. }
  250. if (node.width > node.height) {
  251. x = node.x + node.width / 2;
  252. y = node.y - radius;
  253. }
  254. else {
  255. x = node.x + radius;
  256. y = node.y - node.height / 2;
  257. }
  258. this._circle(ctx, x, y, radius);
  259. point = this._pointOnCircle(x, y, radius, 0.5);
  260. this._label(ctx, this.label, point.x, point.y);
  261. }
  262. };
  263. /**
  264. * Get the line width of the edge. Depends on width and whether one of the
  265. * connected nodes is selected.
  266. * @return {Number} width
  267. * @private
  268. */
  269. Edge.prototype._getLineWidth = function() {
  270. if (this.selected == true) {
  271. return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
  272. }
  273. else {
  274. if (this.hover == true) {
  275. return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
  276. }
  277. else {
  278. return Math.max(this.options.width, 0.3*this.networkScaleInv);
  279. }
  280. }
  281. };
  282. Edge.prototype._getViaCoordinates = function () {
  283. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
  284. return this.via;
  285. }
  286. else if (this.options.smoothCurves.enabled == false) {
  287. return {x:0,y:0};
  288. }
  289. else {
  290. var xVia = null;
  291. var yVia = null;
  292. var factor = this.options.smoothCurves.roundness;
  293. var type = this.options.smoothCurves.type;
  294. var dx = Math.abs(this.from.x - this.to.x);
  295. var dy = Math.abs(this.from.y - this.to.y);
  296. if (type == 'discrete' || type == 'diagonalCross') {
  297. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  298. if (this.from.y > this.to.y) {
  299. if (this.from.x < this.to.x) {
  300. xVia = this.from.x + factor * dy;
  301. yVia = this.from.y - factor * dy;
  302. }
  303. else if (this.from.x > this.to.x) {
  304. xVia = this.from.x - factor * dy;
  305. yVia = this.from.y - factor * dy;
  306. }
  307. }
  308. else if (this.from.y < this.to.y) {
  309. if (this.from.x < this.to.x) {
  310. xVia = this.from.x + factor * dy;
  311. yVia = this.from.y + factor * dy;
  312. }
  313. else if (this.from.x > this.to.x) {
  314. xVia = this.from.x - factor * dy;
  315. yVia = this.from.y + factor * dy;
  316. }
  317. }
  318. if (type == "discrete") {
  319. xVia = dx < factor * dy ? this.from.x : xVia;
  320. }
  321. }
  322. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  323. if (this.from.y > this.to.y) {
  324. if (this.from.x < this.to.x) {
  325. xVia = this.from.x + factor * dx;
  326. yVia = this.from.y - factor * dx;
  327. }
  328. else if (this.from.x > this.to.x) {
  329. xVia = this.from.x - factor * dx;
  330. yVia = this.from.y - factor * dx;
  331. }
  332. }
  333. else if (this.from.y < this.to.y) {
  334. if (this.from.x < this.to.x) {
  335. xVia = this.from.x + factor * dx;
  336. yVia = this.from.y + factor * dx;
  337. }
  338. else if (this.from.x > this.to.x) {
  339. xVia = this.from.x - factor * dx;
  340. yVia = this.from.y + factor * dx;
  341. }
  342. }
  343. if (type == "discrete") {
  344. yVia = dy < factor * dx ? this.from.y : yVia;
  345. }
  346. }
  347. }
  348. else if (type == "straightCross") {
  349. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
  350. xVia = this.from.x;
  351. if (this.from.y < this.to.y) {
  352. yVia = this.to.y - (1 - factor) * dy;
  353. }
  354. else {
  355. yVia = this.to.y + (1 - factor) * dy;
  356. }
  357. }
  358. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
  359. if (this.from.x < this.to.x) {
  360. xVia = this.to.x - (1 - factor) * dx;
  361. }
  362. else {
  363. xVia = this.to.x + (1 - factor) * dx;
  364. }
  365. yVia = this.from.y;
  366. }
  367. }
  368. else if (type == 'horizontal') {
  369. if (this.from.x < this.to.x) {
  370. xVia = this.to.x - (1 - factor) * dx;
  371. }
  372. else {
  373. xVia = this.to.x + (1 - factor) * dx;
  374. }
  375. yVia = this.from.y;
  376. }
  377. else if (type == 'vertical') {
  378. xVia = this.from.x;
  379. if (this.from.y < this.to.y) {
  380. yVia = this.to.y - (1 - factor) * dy;
  381. }
  382. else {
  383. yVia = this.to.y + (1 - factor) * dy;
  384. }
  385. }
  386. else { // continuous
  387. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  388. if (this.from.y > this.to.y) {
  389. if (this.from.x < this.to.x) {
  390. // console.log(1)
  391. xVia = this.from.x + factor * dy;
  392. yVia = this.from.y - factor * dy;
  393. xVia = this.to.x < xVia ? this.to.x : xVia;
  394. }
  395. else if (this.from.x > this.to.x) {
  396. // console.log(2)
  397. xVia = this.from.x - factor * dy;
  398. yVia = this.from.y - factor * dy;
  399. xVia = this.to.x > xVia ? this.to.x : xVia;
  400. }
  401. }
  402. else if (this.from.y < this.to.y) {
  403. if (this.from.x < this.to.x) {
  404. // console.log(3)
  405. xVia = this.from.x + factor * dy;
  406. yVia = this.from.y + factor * dy;
  407. xVia = this.to.x < xVia ? this.to.x : xVia;
  408. }
  409. else if (this.from.x > this.to.x) {
  410. // console.log(4, this.from.x, this.to.x)
  411. xVia = this.from.x - factor * dy;
  412. yVia = this.from.y + factor * dy;
  413. xVia = this.to.x > xVia ? this.to.x : xVia;
  414. }
  415. }
  416. }
  417. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  418. if (this.from.y > this.to.y) {
  419. if (this.from.x < this.to.x) {
  420. // console.log(5)
  421. xVia = this.from.x + factor * dx;
  422. yVia = this.from.y - factor * dx;
  423. yVia = this.to.y > yVia ? this.to.y : yVia;
  424. }
  425. else if (this.from.x > this.to.x) {
  426. // console.log(6)
  427. xVia = this.from.x - factor * dx;
  428. yVia = this.from.y - factor * dx;
  429. yVia = this.to.y > yVia ? this.to.y : yVia;
  430. }
  431. }
  432. else if (this.from.y < this.to.y) {
  433. if (this.from.x < this.to.x) {
  434. // console.log(7)
  435. xVia = this.from.x + factor * dx;
  436. yVia = this.from.y + factor * dx;
  437. yVia = this.to.y < yVia ? this.to.y : yVia;
  438. }
  439. else if (this.from.x > this.to.x) {
  440. // console.log(8)
  441. xVia = this.from.x - factor * dx;
  442. yVia = this.from.y + factor * dx;
  443. yVia = this.to.y < yVia ? this.to.y : yVia;
  444. }
  445. }
  446. }
  447. }
  448. return {x: xVia, y: yVia};
  449. }
  450. };
  451. /**
  452. * Draw a line between two nodes
  453. * @param {CanvasRenderingContext2D} ctx
  454. * @private
  455. */
  456. Edge.prototype._line = function (ctx) {
  457. // draw a straight line
  458. ctx.beginPath();
  459. ctx.moveTo(this.from.x, this.from.y);
  460. if (this.options.smoothCurves.enabled == true) {
  461. if (this.options.smoothCurves.dynamic == false) {
  462. var via = this._getViaCoordinates();
  463. if (via.x == null) {
  464. ctx.lineTo(this.to.x, this.to.y);
  465. ctx.stroke();
  466. return null;
  467. }
  468. else {
  469. // this.via.x = via.x;
  470. // this.via.y = via.y;
  471. ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
  472. ctx.stroke();
  473. return via;
  474. }
  475. }
  476. else {
  477. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  478. ctx.stroke();
  479. return this.via;
  480. }
  481. }
  482. else {
  483. ctx.lineTo(this.to.x, this.to.y);
  484. ctx.stroke();
  485. return null;
  486. }
  487. };
  488. /**
  489. * Draw a line from a node to itself, a circle
  490. * @param {CanvasRenderingContext2D} ctx
  491. * @param {Number} x
  492. * @param {Number} y
  493. * @param {Number} radius
  494. * @private
  495. */
  496. Edge.prototype._circle = function (ctx, x, y, radius) {
  497. // draw a circle
  498. ctx.beginPath();
  499. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  500. ctx.stroke();
  501. };
  502. /**
  503. * Draw label with white background and with the middle at (x, y)
  504. * @param {CanvasRenderingContext2D} ctx
  505. * @param {String} text
  506. * @param {Number} x
  507. * @param {Number} y
  508. * @private
  509. */
  510. Edge.prototype._label = function (ctx, text, x, y) {
  511. if (text) {
  512. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  513. this.options.fontSize + "px " + this.options.fontFace;
  514. var yLine;
  515. if (this.dirtyLabel == true) {
  516. var lines = String(text).split('\n');
  517. var lineCount = lines.length;
  518. var fontSize = Number(this.options.fontSize);
  519. yLine = y + (1 - lineCount) / 2 * fontSize;
  520. var width = ctx.measureText(lines[0]).width;
  521. for (var i = 1; i < lineCount; i++) {
  522. var lineWidth = ctx.measureText(lines[i]).width;
  523. width = lineWidth > width ? lineWidth : width;
  524. }
  525. var height = this.options.fontSize * lineCount;
  526. var left = x - width / 2;
  527. var top = y - height / 2;
  528. // cache
  529. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  530. }
  531. var yLine = this.labelDimensions.yLine;
  532. ctx.save();
  533. if (this.options.labelAlignment != "horizontal"){
  534. ctx.translate(x, yLine);
  535. this._rotateForLabelAlignment(ctx);
  536. x = 0;
  537. yLine = 0;
  538. }
  539. this._drawLabelRect(ctx);
  540. this._drawLabelText(ctx,x,yLine, lines, lineCount, fontSize);
  541. ctx.restore();
  542. }
  543. };
  544. /**
  545. * Rotates the canvas so the text is most readable
  546. * @param {CanvasRenderingContext2D} ctx
  547. * @private
  548. */
  549. Edge.prototype._rotateForLabelAlignment = function(ctx) {
  550. var dy = this.from.y - this.to.y;
  551. var dx = this.from.x - this.to.x;
  552. var angleInDegrees = Math.atan2(dy, dx);
  553. // rotate so label it is readable
  554. if((angleInDegrees < -1 && dx < 0) || (angleInDegrees > 0 && dx < 0)){
  555. angleInDegrees = angleInDegrees + Math.PI;
  556. }
  557. ctx.rotate(angleInDegrees);
  558. };
  559. /**
  560. * Draws the label rectangle
  561. * @param {CanvasRenderingContext2D} ctx
  562. * @param {String} labelAlignment
  563. * @private
  564. */
  565. Edge.prototype._drawLabelRect = function(ctx) {
  566. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  567. ctx.fillStyle = this.options.fontFill;
  568. var lineMargin = 2;
  569. if (this.options.labelAlignment == 'line-center') {
  570. ctx.fillRect(-this.labelDimensions.width * 0.5, -this.labelDimensions.height * 0.5, this.labelDimensions.width, this.labelDimensions.height);
  571. }
  572. else if (this.options.labelAlignment == 'line-above') {
  573. ctx.fillRect(-this.labelDimensions.width * 0.5, -(this.labelDimensions.height + lineMargin), this.labelDimensions.width, this.labelDimensions.height);
  574. }
  575. else if (this.options.labelAlignment == 'line-below') {
  576. ctx.fillRect(-this.labelDimensions.width * 0.5, lineMargin, this.labelDimensions.width, this.labelDimensions.height);
  577. }
  578. else {
  579. ctx.fillStyle = this.options.fontFill;
  580. ctx.fillRect(this.labelDimensions.left, this.labelDimensions.top, this.labelDimensions.width, this.labelDimensions.height);
  581. }
  582. }
  583. };
  584. /**
  585. * Draws the label text
  586. * @param {CanvasRenderingContext2D} ctx
  587. * @param {Number} x
  588. * @param {Number} yLine
  589. * @param {Array} lines
  590. * @param {Number} lineCount
  591. * @param {Number} fontSize
  592. * @private
  593. */
  594. Edge.prototype._drawLabelText = function(ctx, x, yLine, lines, lineCount, fontSize) {
  595. // draw text
  596. ctx.fillStyle = this.options.fontColor || "black";
  597. ctx.textAlign = "center";
  598. // check for label alignment
  599. if (this.options.labelAlignment != 'horizontal') {
  600. var lineMargin = 2;
  601. if (this.options.labelAlignment == 'line-above') {
  602. ctx.textBaseline = "alphabetic";
  603. yLine -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers
  604. }
  605. else if (this.options.labelAlignment == 'line-below') {
  606. ctx.textBaseline = "hanging";
  607. yLine += 2 * lineMargin;// distance from edge, required because we use hanging. Hanging has less difference between browsers
  608. }
  609. else {
  610. ctx.textBaseline = "middle";
  611. }
  612. }
  613. // check for strokeWidth
  614. if (this.options.fontStrokeWidth > 0){
  615. ctx.lineWidth = this.options.fontStrokeWidth;
  616. ctx.strokeStyle = this.options.fontStrokeColor;
  617. ctx.lineJoin = 'round';
  618. }
  619. for (var i = 0; i < lineCount; i++) {
  620. if(this.options.fontStrokeWidth > 0){
  621. ctx.strokeText(lines[i], x, yLine);
  622. }
  623. ctx.fillText(lines[i], x, yLine);
  624. yLine += fontSize;
  625. }
  626. };
  627. /**
  628. * Redraw a edge as a dashed line
  629. * Draw this edge in the given canvas
  630. * @author David Jordan
  631. * @date 2012-08-08
  632. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  633. * @param {CanvasRenderingContext2D} ctx
  634. * @private
  635. */
  636. Edge.prototype._drawDashLine = function(ctx) {
  637. // set style
  638. ctx.strokeStyle = this._getColor();
  639. ctx.lineWidth = this._getLineWidth();
  640. var via = null;
  641. // only firefox and chrome support this method, else we use the legacy one.
  642. if (ctx.setLineDash !== undefined) {
  643. ctx.save();
  644. // configure the dash pattern
  645. var pattern = [0];
  646. if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
  647. pattern = [this.options.dash.length,this.options.dash.gap];
  648. }
  649. else {
  650. pattern = [5,5];
  651. }
  652. // set dash settings for chrome or firefox
  653. ctx.setLineDash(pattern);
  654. ctx.lineDashOffset = 0;
  655. // draw the line
  656. via = this._line(ctx);
  657. // restore the dash settings.
  658. ctx.setLineDash([0]);
  659. ctx.lineDashOffset = 0;
  660. ctx.restore();
  661. }
  662. else { // unsupporting smooth lines
  663. // draw dashed line
  664. ctx.beginPath();
  665. ctx.lineCap = 'round';
  666. if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  667. {
  668. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  669. [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
  670. }
  671. else if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value
  672. {
  673. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  674. [this.options.dash.length,this.options.dash.gap]);
  675. }
  676. else //If all else fails draw a line
  677. {
  678. ctx.moveTo(this.from.x, this.from.y);
  679. ctx.lineTo(this.to.x, this.to.y);
  680. }
  681. ctx.stroke();
  682. }
  683. // draw label
  684. if (this.label) {
  685. var point;
  686. if (this.options.smoothCurves.enabled == true && via != null) {
  687. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  688. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  689. point = {x:midpointX, y:midpointY};
  690. }
  691. else {
  692. point = this._pointOnLine(0.5);
  693. }
  694. this._label(ctx, this.label, point.x, point.y);
  695. }
  696. };
  697. /**
  698. * Get a point on a line
  699. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  700. * @return {Object} point
  701. * @private
  702. */
  703. Edge.prototype._pointOnLine = function (percentage) {
  704. return {
  705. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  706. y: (1 - percentage) * this.from.y + percentage * this.to.y
  707. }
  708. };
  709. /**
  710. * Get a point on a circle
  711. * @param {Number} x
  712. * @param {Number} y
  713. * @param {Number} radius
  714. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  715. * @return {Object} point
  716. * @private
  717. */
  718. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  719. var angle = (percentage - 3/8) * 2 * Math.PI;
  720. return {
  721. x: x + radius * Math.cos(angle),
  722. y: y - radius * Math.sin(angle)
  723. }
  724. };
  725. /**
  726. * Redraw a edge as a line with an arrow halfway the line
  727. * Draw this edge in the given canvas
  728. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  729. * @param {CanvasRenderingContext2D} ctx
  730. * @private
  731. */
  732. Edge.prototype._drawArrowCenter = function(ctx) {
  733. var point;
  734. // set style
  735. ctx.strokeStyle = this._getColor();
  736. ctx.fillStyle = ctx.strokeStyle;
  737. ctx.lineWidth = this._getLineWidth();
  738. if (this.from != this.to) {
  739. // draw line
  740. var via = this._line(ctx);
  741. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  742. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  743. // draw an arrow halfway the line
  744. if (this.options.smoothCurves.enabled == true && via != null) {
  745. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  746. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  747. point = {x:midpointX, y:midpointY};
  748. }
  749. else {
  750. point = this._pointOnLine(0.5);
  751. }
  752. ctx.arrow(point.x, point.y, angle, length);
  753. ctx.fill();
  754. ctx.stroke();
  755. // draw label
  756. if (this.label) {
  757. this._label(ctx, this.label, point.x, point.y);
  758. }
  759. }
  760. else {
  761. // draw circle
  762. var x, y;
  763. var radius = 0.25 * Math.max(100,this.physics.springLength);
  764. var node = this.from;
  765. if (!node.width) {
  766. node.resize(ctx);
  767. }
  768. if (node.width > node.height) {
  769. x = node.x + node.width * 0.5;
  770. y = node.y - radius;
  771. }
  772. else {
  773. x = node.x + radius;
  774. y = node.y - node.height * 0.5;
  775. }
  776. this._circle(ctx, x, y, radius);
  777. // draw all arrows
  778. var angle = 0.2 * Math.PI;
  779. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  780. point = this._pointOnCircle(x, y, radius, 0.5);
  781. ctx.arrow(point.x, point.y, angle, length);
  782. ctx.fill();
  783. ctx.stroke();
  784. // draw label
  785. if (this.label) {
  786. point = this._pointOnCircle(x, y, radius, 0.5);
  787. this._label(ctx, this.label, point.x, point.y);
  788. }
  789. }
  790. };
  791. Edge.prototype._pointOnBezier = function(t) {
  792. var via = this._getViaCoordinates();
  793. var x = Math.pow(1-t,2)*this.from.x + (2*t*(1 - t))*via.x + Math.pow(t,2)*this.to.x;
  794. var y = Math.pow(1-t,2)*this.from.y + (2*t*(1 - t))*via.y + Math.pow(t,2)*this.to.y;
  795. return {x:x,y:y};
  796. }
  797. /**
  798. * This function uses binary search to look for the point where the bezier curve crosses the border of the node.
  799. *
  800. * @param from
  801. * @param ctx
  802. * @returns {*}
  803. * @private
  804. */
  805. Edge.prototype._findBorderPosition = function(from,ctx) {
  806. var maxIterations = 10;
  807. var iteration = 0;
  808. var low = 0;
  809. var high = 1;
  810. var pos,angle,distanceToBorder, distanceToNodes, difference;
  811. var threshold = 0.2;
  812. var node = this.to;
  813. if (from == true) {
  814. node = this.from;
  815. }
  816. while (low <= high && iteration < maxIterations) {
  817. var middle = (low + high) * 0.5;
  818. pos = this._pointOnBezier(middle);
  819. angle = Math.atan2((node.y - pos.y), (node.x - pos.x));
  820. distanceToBorder = node.distanceToBorder(ctx,angle);
  821. distanceToNodes = Math.sqrt(Math.pow(pos.x-node.x,2) + Math.pow(pos.y-node.y,2));
  822. difference = distanceToBorder - distanceToNodes;
  823. if (Math.abs(difference) < threshold) {
  824. break; // found
  825. }
  826. else if (difference < 0) { // distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
  827. if (from == false) {
  828. low = middle;
  829. }
  830. else {
  831. high = middle;
  832. }
  833. }
  834. else {
  835. if (from == false) {
  836. high = middle;
  837. }
  838. else {
  839. low = middle;
  840. }
  841. }
  842. iteration++;
  843. }
  844. pos.t = middle;
  845. return pos;
  846. };
  847. /**
  848. * Redraw a edge as a line with an arrow
  849. * Draw this edge in the given canvas
  850. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  851. * @param {CanvasRenderingContext2D} ctx
  852. * @private
  853. */
  854. Edge.prototype._drawArrow = function(ctx) {
  855. // set style
  856. ctx.strokeStyle = this._getColor();
  857. ctx.fillStyle = ctx.strokeStyle;
  858. ctx.lineWidth = this._getLineWidth();
  859. // set vars
  860. var angle, length, arrowPos;
  861. // if not connected to itself
  862. if (this.from != this.to) {
  863. // draw line
  864. this._line(ctx);
  865. // draw arrow head
  866. if (this.options.smoothCurves.enabled == true) {
  867. var via = this._getViaCoordinates();
  868. arrowPos = this._findBorderPosition(false, ctx);
  869. var guidePos = this._pointOnBezier(Math.max(0.0, arrowPos.t - 0.1))
  870. angle = Math.atan2((arrowPos.y - guidePos.y), (arrowPos.x - guidePos.x));
  871. }
  872. else {
  873. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  874. var dx = (this.to.x - this.from.x);
  875. var dy = (this.to.y - this.from.y);
  876. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  877. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  878. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  879. arrowPos = {};
  880. arrowPos.x = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  881. arrowPos.y = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  882. }
  883. // draw arrow at the end of the line
  884. length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  885. ctx.arrow(arrowPos.x,arrowPos.y, angle, length);
  886. ctx.fill();
  887. ctx.stroke();
  888. // draw label
  889. if (this.label) {
  890. var point;
  891. if (this.options.smoothCurves.enabled == true && via != null) {
  892. point = this._pointOnBezier(0.5);
  893. }
  894. else {
  895. point = this._pointOnLine(0.5);
  896. }
  897. this._label(ctx, this.label, point.x, point.y);
  898. }
  899. }
  900. else {
  901. // draw circle
  902. var node = this.from;
  903. var x, y, arrow;
  904. var radius = 0.25 * Math.max(100,this.physics.springLength);
  905. if (!node.width) {
  906. node.resize(ctx);
  907. }
  908. if (node.width > node.height) {
  909. x = node.x + node.width * 0.5;
  910. y = node.y - radius;
  911. arrow = {
  912. x: x,
  913. y: node.y,
  914. angle: 0.9 * Math.PI
  915. };
  916. }
  917. else {
  918. x = node.x + radius;
  919. y = node.y - node.height * 0.5;
  920. arrow = {
  921. x: node.x,
  922. y: y,
  923. angle: 0.6 * Math.PI
  924. };
  925. }
  926. ctx.beginPath();
  927. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  928. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  929. ctx.stroke();
  930. // draw all arrows
  931. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  932. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  933. ctx.fill();
  934. ctx.stroke();
  935. // draw label
  936. if (this.label) {
  937. point = this._pointOnCircle(x, y, radius, 0.5);
  938. this._label(ctx, this.label, point.x, point.y);
  939. }
  940. }
  941. };
  942. /**
  943. * Calculate the distance between a point (x3,y3) and a line segment from
  944. * (x1,y1) to (x2,y2).
  945. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  946. * @param {number} x1
  947. * @param {number} y1
  948. * @param {number} x2
  949. * @param {number} y2
  950. * @param {number} x3
  951. * @param {number} y3
  952. * @private
  953. */
  954. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  955. var returnValue = 0;
  956. if (this.from != this.to) {
  957. if (this.options.smoothCurves.enabled == true) {
  958. var xVia, yVia;
  959. if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
  960. xVia = this.via.x;
  961. yVia = this.via.y;
  962. }
  963. else {
  964. var via = this._getViaCoordinates();
  965. xVia = via.x;
  966. yVia = via.y;
  967. }
  968. var minDistance = 1e9;
  969. var distance;
  970. var i,t,x,y, lastX, lastY;
  971. for (i = 0; i < 10; i++) {
  972. t = 0.1*i;
  973. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
  974. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
  975. if (i > 0) {
  976. distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
  977. minDistance = distance < minDistance ? distance : minDistance;
  978. }
  979. lastX = x; lastY = y;
  980. }
  981. returnValue = minDistance;
  982. }
  983. else {
  984. returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
  985. }
  986. }
  987. else {
  988. var x, y, dx, dy;
  989. var radius = 0.25 * this.physics.springLength;
  990. var node = this.from;
  991. if (node.width > node.height) {
  992. x = node.x + 0.5 * node.width;
  993. y = node.y - radius;
  994. }
  995. else {
  996. x = node.x + radius;
  997. y = node.y - 0.5 * node.height;
  998. }
  999. dx = x - x3;
  1000. dy = y - y3;
  1001. returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
  1002. }
  1003. if (this.labelDimensions.left < x3 &&
  1004. this.labelDimensions.left + this.labelDimensions.width > x3 &&
  1005. this.labelDimensions.top < y3 &&
  1006. this.labelDimensions.top + this.labelDimensions.height > y3) {
  1007. return 0;
  1008. }
  1009. else {
  1010. return returnValue;
  1011. }
  1012. };
  1013. Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
  1014. var px = x2-x1,
  1015. py = y2-y1,
  1016. something = px*px + py*py,
  1017. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  1018. if (u > 1) {
  1019. u = 1;
  1020. }
  1021. else if (u < 0) {
  1022. u = 0;
  1023. }
  1024. var x = x1 + u * px,
  1025. y = y1 + u * py,
  1026. dx = x - x3,
  1027. dy = y - y3;
  1028. //# Note: If the actual distance does not matter,
  1029. //# if you only want to compare what this function
  1030. //# returns to other results of this function, you
  1031. //# can just return the squared distance instead
  1032. //# (i.e. remove the sqrt) to gain a little performance
  1033. return Math.sqrt(dx*dx + dy*dy);
  1034. };
  1035. /**
  1036. * This allows the zoom level of the network to influence the rendering
  1037. *
  1038. * @param scale
  1039. */
  1040. Edge.prototype.setScale = function(scale) {
  1041. this.networkScaleInv = 1.0/scale;
  1042. };
  1043. Edge.prototype.select = function() {
  1044. this.selected = true;
  1045. };
  1046. Edge.prototype.unselect = function() {
  1047. this.selected = false;
  1048. };
  1049. Edge.prototype.positionBezierNode = function() {
  1050. if (this.via !== null && this.from !== null && this.to !== null) {
  1051. this.via.x = 0.5 * (this.from.x + this.to.x);
  1052. this.via.y = 0.5 * (this.from.y + this.to.y);
  1053. }
  1054. else {
  1055. this.via.x = 0;
  1056. this.via.y = 0;
  1057. }
  1058. };
  1059. /**
  1060. * This function draws the control nodes for the manipulator.
  1061. * In order to enable this, only set the this.controlNodesEnabled to true.
  1062. * @param ctx
  1063. */
  1064. Edge.prototype._drawControlNodes = function(ctx) {
  1065. if (this.controlNodesEnabled == true) {
  1066. if (this.controlNodes.from === null && this.controlNodes.to === null) {
  1067. var nodeIdFrom = "edgeIdFrom:".concat(this.id);
  1068. var nodeIdTo = "edgeIdTo:".concat(this.id);
  1069. var constants = {
  1070. nodes:{group:'', radius:7, borderWidth:2, borderWidthSelected: 2},
  1071. physics:{damping:0},
  1072. clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
  1073. };
  1074. this.controlNodes.from = new Node(
  1075. {id:nodeIdFrom,
  1076. shape:'dot',
  1077. color:{background:'#ff0000', border:'#3c3c3c', highlight: {background:'#07f968'}}
  1078. },{},{},constants);
  1079. this.controlNodes.to = new Node(
  1080. {id:nodeIdTo,
  1081. shape:'dot',
  1082. color:{background:'#ff0000', border:'#3c3c3c', highlight: {background:'#07f968'}}
  1083. },{},{},constants);
  1084. }
  1085. this.controlNodes.positions = {};
  1086. if (this.controlNodes.from.selected == false) {
  1087. this.controlNodes.positions.from = this.getControlNodeFromPosition(ctx);
  1088. this.controlNodes.from.x = this.controlNodes.positions.from.x;
  1089. this.controlNodes.from.y = this.controlNodes.positions.from.y;
  1090. }
  1091. if (this.controlNodes.to.selected == false) {
  1092. this.controlNodes.positions.to = this.getControlNodeToPosition(ctx);
  1093. this.controlNodes.to.x = this.controlNodes.positions.to.x;
  1094. this.controlNodes.to.y = this.controlNodes.positions.to.y;
  1095. }
  1096. this.controlNodes.from.draw(ctx);
  1097. this.controlNodes.to.draw(ctx);
  1098. }
  1099. else {
  1100. this.controlNodes = {from:null, to:null, positions:{}};
  1101. }
  1102. };
  1103. /**
  1104. * Enable control nodes.
  1105. * @private
  1106. */
  1107. Edge.prototype._enableControlNodes = function() {
  1108. this.fromBackup = this.from;
  1109. this.toBackup = this.to;
  1110. this.controlNodesEnabled = true;
  1111. };
  1112. /**
  1113. * disable control nodes and remove from dynamicEdges from old node
  1114. * @private
  1115. */
  1116. Edge.prototype._disableControlNodes = function() {
  1117. this.fromId = this.from.id;
  1118. this.toId = this.to.id;
  1119. if (this.fromId != this.fromBackup.id) { // from was changed, remove edge from old 'from' node dynamic edges
  1120. this.fromBackup.detachEdge(this);
  1121. }
  1122. else if (this.toId != this.toBackup.id) { // to was changed, remove edge from old 'to' node dynamic edges
  1123. this.toBackup.detachEdge(this);
  1124. }
  1125. this.fromBackup = null;
  1126. this.toBackup = null;
  1127. this.controlNodesEnabled = false;
  1128. };
  1129. /**
  1130. * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
  1131. * @param x
  1132. * @param y
  1133. * @returns {null}
  1134. * @private
  1135. */
  1136. Edge.prototype._getSelectedControlNode = function(x,y) {
  1137. var positions = this.controlNodes.positions;
  1138. var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
  1139. var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
  1140. if (fromDistance < 15) {
  1141. this.connectedNode = this.from;
  1142. this.from = this.controlNodes.from;
  1143. return this.controlNodes.from;
  1144. }
  1145. else if (toDistance < 15) {
  1146. this.connectedNode = this.to;
  1147. this.to = this.controlNodes.to;
  1148. return this.controlNodes.to;
  1149. }
  1150. else {
  1151. return null;
  1152. }
  1153. };
  1154. /**
  1155. * this resets the control nodes to their original position.
  1156. * @private
  1157. */
  1158. Edge.prototype._restoreControlNodes = function() {
  1159. if (this.controlNodes.from.selected == true) {
  1160. this.from = this.connectedNode;
  1161. this.connectedNode = null;
  1162. this.controlNodes.from.unselect();
  1163. }
  1164. else if (this.controlNodes.to.selected == true) {
  1165. this.to = this.connectedNode;
  1166. this.connectedNode = null;
  1167. this.controlNodes.to.unselect();
  1168. }
  1169. };
  1170. /**
  1171. * this calculates the position of the control nodes on the edges of the parent nodes.
  1172. *
  1173. * @param ctx
  1174. * @returns {x: *, y: *}
  1175. */
  1176. Edge.prototype.getControlNodeFromPosition = function(ctx) {
  1177. // draw arrow head
  1178. var controlnodeFromPos;
  1179. if (this.options.smoothCurves.enabled == true) {
  1180. controlnodeFromPos = this._findBorderPosition(true, ctx);
  1181. }
  1182. else {
  1183. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  1184. var dx = (this.to.x - this.from.x);
  1185. var dy = (this.to.y - this.from.y);
  1186. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  1187. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  1188. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  1189. controlnodeFromPos = {};
  1190. controlnodeFromPos.x = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  1191. controlnodeFromPos.y = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  1192. }
  1193. return controlnodeFromPos;
  1194. };
  1195. /**
  1196. * this calculates the position of the control nodes on the edges of the parent nodes.
  1197. *
  1198. * @param ctx
  1199. * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
  1200. */
  1201. Edge.prototype.getControlNodeToPosition = function(ctx) {
  1202. // draw arrow head
  1203. var controlnodeFromPos,controlnodeToPos;
  1204. if (this.options.smoothCurves.enabled == true) {
  1205. controlnodeToPos = this._findBorderPosition(false, ctx);
  1206. }
  1207. else {
  1208. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  1209. var dx = (this.to.x - this.from.x);
  1210. var dy = (this.to.y - this.from.y);
  1211. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  1212. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  1213. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  1214. controlnodeToPos = {};
  1215. controlnodeToPos.x = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  1216. controlnodeToPos.y = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  1217. }
  1218. return controlnodeToPos;
  1219. };
  1220. module.exports = Edge;