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.

1018 lines
35 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var util = require('../util');
  2. /**
  3. * @class Node
  4. * A node. A node can be connected to other nodes via one or multiple edges.
  5. * @param {object} properties An object containing properties for the node. All
  6. * properties are optional, except for the id.
  7. * {number} id Id of the node. Required
  8. * {string} label Text label for the node
  9. * {number} x Horizontal position of the node
  10. * {number} y Vertical position of the node
  11. * {string} shape Node shape, available:
  12. * "database", "circle", "ellipse",
  13. * "box", "image", "text", "dot",
  14. * "star", "triangle", "triangleDown",
  15. * "square"
  16. * {string} image An image url
  17. * {string} title An title text, can be HTML
  18. * {anytype} group A group name or number
  19. * @param {Network.Images} imagelist A list with images. Only needed
  20. * when the node has an image
  21. * @param {Network.Groups} grouplist A list with groups. Needed for
  22. * retrieving group properties
  23. * @param {Object} constants An object with default values for
  24. * example for the color
  25. *
  26. */
  27. function Node(properties, imagelist, grouplist, networkConstants) {
  28. var constants = util.selectiveBridgeObject(['nodes'],networkConstants);
  29. this.options = constants.nodes;
  30. this.selected = false;
  31. this.hover = false;
  32. this.edges = []; // all edges connected to this node
  33. this.dynamicEdges = [];
  34. this.reroutedEdges = {};
  35. this.fontDrawThreshold = 3;
  36. // set defaults for the properties
  37. this.id = undefined;
  38. this.x = null;
  39. this.y = null;
  40. this.allowedToMoveX = false;
  41. this.allowedToMoveY = false;
  42. this.xFixed = false;
  43. this.yFixed = false;
  44. this.horizontalAlignLeft = true; // these are for the navigation controls
  45. this.verticalAlignTop = true; // these are for the navigation controls
  46. this.baseRadiusValue = networkConstants.nodes.radius;
  47. this.radiusFixed = false;
  48. this.level = -1;
  49. this.preassignedLevel = false;
  50. this.hierarchyEnumerated = false;
  51. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  52. this.imagelist = imagelist;
  53. this.grouplist = grouplist;
  54. // physics properties
  55. this.fx = 0.0; // external force x
  56. this.fy = 0.0; // external force y
  57. this.vx = 0.0; // velocity x
  58. this.vy = 0.0; // velocity y
  59. this.damping = networkConstants.physics.damping; // written every time gravity is calculated
  60. this.fixedData = {x:null,y:null};
  61. this.setProperties(properties, constants);
  62. // creating the variables for clustering
  63. this.resetCluster();
  64. this.dynamicEdgesLength = 0;
  65. this.clusterSession = 0;
  66. this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width;
  67. this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height;
  68. this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius;
  69. this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements;
  70. this.growthIndicator = 0;
  71. // variables to tell the node about the network.
  72. this.networkScaleInv = 1;
  73. this.networkScale = 1;
  74. this.canvasTopLeft = {"x": -300, "y": -300};
  75. this.canvasBottomRight = {"x": 300, "y": 300};
  76. this.parentEdgeId = null;
  77. }
  78. /**
  79. * (re)setting the clustering variables and objects
  80. */
  81. Node.prototype.resetCluster = function() {
  82. // clustering variables
  83. this.formationScale = undefined; // this is used to determine when to open the cluster
  84. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  85. this.containedNodes = {};
  86. this.containedEdges = {};
  87. this.clusterSessions = [];
  88. };
  89. /**
  90. * Attach a edge to the node
  91. * @param {Edge} edge
  92. */
  93. Node.prototype.attachEdge = function(edge) {
  94. if (this.edges.indexOf(edge) == -1) {
  95. this.edges.push(edge);
  96. }
  97. if (this.dynamicEdges.indexOf(edge) == -1) {
  98. this.dynamicEdges.push(edge);
  99. }
  100. this.dynamicEdgesLength = this.dynamicEdges.length;
  101. };
  102. /**
  103. * Detach a edge from the node
  104. * @param {Edge} edge
  105. */
  106. Node.prototype.detachEdge = function(edge) {
  107. var index = this.edges.indexOf(edge);
  108. if (index != -1) {
  109. this.edges.splice(index, 1);
  110. }
  111. index = this.dynamicEdges.indexOf(edge);
  112. if (index != -1) {
  113. this.dynamicEdges.splice(index, 1);
  114. }
  115. this.dynamicEdgesLength = this.dynamicEdges.length;
  116. };
  117. /**
  118. * Set or overwrite properties for the node
  119. * @param {Object} properties an object with properties
  120. * @param {Object} constants and object with default, global properties
  121. */
  122. Node.prototype.setProperties = function(properties, constants) {
  123. if (!properties) {
  124. return;
  125. }
  126. var fields = ['borderWidth','borderWidthSelected','shape','image','brokenImage','radius','fontColor',
  127. 'fontSize','fontFace','fontFill','group','mass'
  128. ];
  129. util.selectiveDeepExtend(fields, this.options, properties);
  130. // basic properties
  131. if (properties.id !== undefined) {this.id = properties.id;}
  132. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  133. if (properties.title !== undefined) {this.title = properties.title;}
  134. if (properties.x !== undefined) {this.x = properties.x;}
  135. if (properties.y !== undefined) {this.y = properties.y;}
  136. if (properties.value !== undefined) {this.value = properties.value;}
  137. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  138. // navigation controls properties
  139. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  140. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  141. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  142. if (this.id === undefined) {
  143. throw "Node must have an id";
  144. }
  145. // copy group properties
  146. if (typeof this.options.group === 'number' || (typeof this.options.group === 'string' && this.options.group != '')) {
  147. var groupObj = this.grouplist.get(this.options.group);
  148. for (var prop in groupObj) {
  149. if (groupObj.hasOwnProperty(prop)) {
  150. this.options[prop] = groupObj[prop];
  151. }
  152. }
  153. }
  154. // individual shape properties
  155. if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;}
  156. if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);}
  157. if (this.options.image!== undefined && this.options.image!= "") {
  158. if (this.imagelist) {
  159. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage);
  160. }
  161. else {
  162. throw "No imagelist provided";
  163. }
  164. }
  165. if (properties.allowedToMoveX !== undefined) {
  166. this.xFixed = !properties.allowedToMoveX;
  167. this.allowedToMoveX = properties.allowedToMoveX;
  168. }
  169. else if (properties.x !== undefined && this.allowedToMoveX == false) {
  170. this.xFixed = true;
  171. }
  172. if (properties.allowedToMoveY !== undefined) {
  173. this.yFixed = !properties.allowedToMoveY;
  174. this.allowedToMoveY = properties.allowedToMoveY;
  175. }
  176. else if (properties.y !== undefined && this.allowedToMoveY == false) {
  177. this.yFixed = true;
  178. }
  179. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  180. if (this.options.shape == 'image') {
  181. this.options.radiusMin = constants.nodes.widthMin;
  182. this.options.radiusMax = constants.nodes.widthMax;
  183. }
  184. // choose draw method depending on the shape
  185. switch (this.options.shape) {
  186. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  187. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  188. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  189. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  190. // TODO: add diamond shape
  191. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  192. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  193. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  194. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  195. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  196. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  197. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  198. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  199. }
  200. // reset the size of the node, this can be changed
  201. this._reset();
  202. };
  203. /**
  204. * select this node
  205. */
  206. Node.prototype.select = function() {
  207. this.selected = true;
  208. this._reset();
  209. };
  210. /**
  211. * unselect this node
  212. */
  213. Node.prototype.unselect = function() {
  214. this.selected = false;
  215. this._reset();
  216. };
  217. /**
  218. * Reset the calculated size of the node, forces it to recalculate its size
  219. */
  220. Node.prototype.clearSizeCache = function() {
  221. this._reset();
  222. };
  223. /**
  224. * Reset the calculated size of the node, forces it to recalculate its size
  225. * @private
  226. */
  227. Node.prototype._reset = function() {
  228. this.width = undefined;
  229. this.height = undefined;
  230. };
  231. /**
  232. * get the title of this node.
  233. * @return {string} title The title of the node, or undefined when no title
  234. * has been set.
  235. */
  236. Node.prototype.getTitle = function() {
  237. return typeof this.title === "function" ? this.title() : this.title;
  238. };
  239. /**
  240. * Calculate the distance to the border of the Node
  241. * @param {CanvasRenderingContext2D} ctx
  242. * @param {Number} angle Angle in radians
  243. * @returns {number} distance Distance to the border in pixels
  244. */
  245. Node.prototype.distanceToBorder = function (ctx, angle) {
  246. var borderWidth = 1;
  247. if (!this.width) {
  248. this.resize(ctx);
  249. }
  250. switch (this.options.shape) {
  251. case 'circle':
  252. case 'dot':
  253. return this.options.radius+ borderWidth;
  254. case 'ellipse':
  255. var a = this.width / 2;
  256. var b = this.height / 2;
  257. var w = (Math.sin(angle) * a);
  258. var h = (Math.cos(angle) * b);
  259. return a * b / Math.sqrt(w * w + h * h);
  260. // TODO: implement distanceToBorder for database
  261. // TODO: implement distanceToBorder for triangle
  262. // TODO: implement distanceToBorder for triangleDown
  263. case 'box':
  264. case 'image':
  265. case 'text':
  266. default:
  267. if (this.width) {
  268. return Math.min(
  269. Math.abs(this.width / 2 / Math.cos(angle)),
  270. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  271. // TODO: reckon with border radius too in case of box
  272. }
  273. else {
  274. return 0;
  275. }
  276. }
  277. // TODO: implement calculation of distance to border for all shapes
  278. };
  279. /**
  280. * Set forces acting on the node
  281. * @param {number} fx Force in horizontal direction
  282. * @param {number} fy Force in vertical direction
  283. */
  284. Node.prototype._setForce = function(fx, fy) {
  285. this.fx = fx;
  286. this.fy = fy;
  287. };
  288. /**
  289. * Add forces acting on the node
  290. * @param {number} fx Force in horizontal direction
  291. * @param {number} fy Force in vertical direction
  292. * @private
  293. */
  294. Node.prototype._addForce = function(fx, fy) {
  295. this.fx += fx;
  296. this.fy += fy;
  297. };
  298. /**
  299. * Perform one discrete step for the node
  300. * @param {number} interval Time interval in seconds
  301. */
  302. Node.prototype.discreteStep = function(interval) {
  303. if (!this.xFixed) {
  304. var dx = this.damping * this.vx; // damping force
  305. var ax = (this.fx - dx) / this.options.mass; // acceleration
  306. this.vx += ax * interval; // velocity
  307. this.x += this.vx * interval; // position
  308. }
  309. else {
  310. this.fx = 0;
  311. this.vx = 0;
  312. }
  313. if (!this.yFixed) {
  314. var dy = this.damping * this.vy; // damping force
  315. var ay = (this.fy - dy) / this.options.mass; // acceleration
  316. this.vy += ay * interval; // velocity
  317. this.y += this.vy * interval; // position
  318. }
  319. else {
  320. this.fy = 0;
  321. this.vy = 0;
  322. }
  323. };
  324. /**
  325. * Perform one discrete step for the node
  326. * @param {number} interval Time interval in seconds
  327. * @param {number} maxVelocity The speed limit imposed on the velocity
  328. */
  329. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  330. if (!this.xFixed) {
  331. var dx = this.damping * this.vx; // damping force
  332. var ax = (this.fx - dx) / this.options.mass; // acceleration
  333. this.vx += ax * interval; // velocity
  334. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  335. this.x += this.vx * interval; // position
  336. }
  337. else {
  338. this.fx = 0;
  339. this.vx = 0;
  340. }
  341. if (!this.yFixed) {
  342. var dy = this.damping * this.vy; // damping force
  343. var ay = (this.fy - dy) / this.options.mass; // acceleration
  344. this.vy += ay * interval; // velocity
  345. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  346. this.y += this.vy * interval; // position
  347. }
  348. else {
  349. this.fy = 0;
  350. this.vy = 0;
  351. }
  352. };
  353. /**
  354. * Check if this node has a fixed x and y position
  355. * @return {boolean} true if fixed, false if not
  356. */
  357. Node.prototype.isFixed = function() {
  358. return (this.xFixed && this.yFixed);
  359. };
  360. /**
  361. * Check if this node is moving
  362. * @param {number} vmin the minimum velocity considered as "moving"
  363. * @return {boolean} true if moving, false if it has no velocity
  364. */
  365. Node.prototype.isMoving = function(vmin) {
  366. var velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2));
  367. // this.velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2))
  368. return (velocity > vmin);
  369. };
  370. /**
  371. * check if this node is selecte
  372. * @return {boolean} selected True if node is selected, else false
  373. */
  374. Node.prototype.isSelected = function() {
  375. return this.selected;
  376. };
  377. /**
  378. * Retrieve the value of the node. Can be undefined
  379. * @return {Number} value
  380. */
  381. Node.prototype.getValue = function() {
  382. return this.value;
  383. };
  384. /**
  385. * Calculate the distance from the nodes location to the given location (x,y)
  386. * @param {Number} x
  387. * @param {Number} y
  388. * @return {Number} value
  389. */
  390. Node.prototype.getDistance = function(x, y) {
  391. var dx = this.x - x,
  392. dy = this.y - y;
  393. return Math.sqrt(dx * dx + dy * dy);
  394. };
  395. /**
  396. * Adjust the value range of the node. The node will adjust it's radius
  397. * based on its value.
  398. * @param {Number} min
  399. * @param {Number} max
  400. */
  401. Node.prototype.setValueRange = function(min, max) {
  402. if (!this.radiusFixed && this.value !== undefined) {
  403. if (max == min) {
  404. this.options.radius= (this.options.radiusMin + this.options.radiusMax) / 2;
  405. }
  406. else {
  407. var scale = (this.options.radiusMax - this.options.radiusMin) / (max - min);
  408. this.options.radius= (this.value - min) * scale + this.options.radiusMin;
  409. }
  410. }
  411. this.baseRadiusValue = this.options.radius;
  412. };
  413. /**
  414. * Draw this node in the given canvas
  415. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  416. * @param {CanvasRenderingContext2D} ctx
  417. */
  418. Node.prototype.draw = function(ctx) {
  419. throw "Draw method not initialized for node";
  420. };
  421. /**
  422. * Recalculate the size of this node in the given canvas
  423. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  424. * @param {CanvasRenderingContext2D} ctx
  425. */
  426. Node.prototype.resize = function(ctx) {
  427. throw "Resize method not initialized for node";
  428. };
  429. /**
  430. * Check if this object is overlapping with the provided object
  431. * @param {Object} obj an object with parameters left, top, right, bottom
  432. * @return {boolean} True if location is located on node
  433. */
  434. Node.prototype.isOverlappingWith = function(obj) {
  435. return (this.left < obj.right &&
  436. this.left + this.width > obj.left &&
  437. this.top < obj.bottom &&
  438. this.top + this.height > obj.top);
  439. };
  440. Node.prototype._resizeImage = function (ctx) {
  441. // TODO: pre calculate the image size
  442. if (!this.width || !this.height) { // undefined or 0
  443. var width, height;
  444. if (this.value) {
  445. this.options.radius= this.baseRadiusValue;
  446. var scale = this.imageObj.height / this.imageObj.width;
  447. if (scale !== undefined) {
  448. width = this.options.radius|| this.imageObj.width;
  449. height = this.options.radius* scale || this.imageObj.height;
  450. }
  451. else {
  452. width = 0;
  453. height = 0;
  454. }
  455. }
  456. else {
  457. width = this.imageObj.width;
  458. height = this.imageObj.height;
  459. }
  460. this.width = width;
  461. this.height = height;
  462. this.growthIndicator = 0;
  463. if (this.width > 0 && this.height > 0) {
  464. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  465. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  466. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  467. this.growthIndicator = this.width - width;
  468. }
  469. }
  470. };
  471. Node.prototype._drawImage = function (ctx) {
  472. this._resizeImage(ctx);
  473. this.left = this.x - this.width / 2;
  474. this.top = this.y - this.height / 2;
  475. var yLabel;
  476. if (this.imageObj.width != 0 ) {
  477. // draw the shade
  478. if (this.clusterSize > 1) {
  479. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  480. lineWidth *= this.networkScaleInv;
  481. lineWidth = Math.min(0.2 * this.width,lineWidth);
  482. ctx.globalAlpha = 0.5;
  483. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  484. }
  485. // draw the image
  486. ctx.globalAlpha = 1.0;
  487. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  488. yLabel = this.y + this.height / 2;
  489. }
  490. else {
  491. // image still loading... just draw the label for now
  492. yLabel = this.y;
  493. }
  494. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  495. };
  496. Node.prototype._resizeBox = function (ctx) {
  497. if (!this.width) {
  498. var margin = 5;
  499. var textSize = this.getTextSize(ctx);
  500. this.width = textSize.width + 2 * margin;
  501. this.height = textSize.height + 2 * margin;
  502. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  503. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  504. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  505. // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  506. }
  507. };
  508. Node.prototype._drawBox = function (ctx) {
  509. this._resizeBox(ctx);
  510. this.left = this.x - this.width / 2;
  511. this.top = this.y - this.height / 2;
  512. var clusterLineWidth = 2.5;
  513. var borderWidth = this.options.borderWidth;
  514. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  515. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  516. // draw the outer border
  517. if (this.clusterSize > 1) {
  518. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  519. ctx.lineWidth *= this.networkScaleInv;
  520. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  521. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.options.radius);
  522. ctx.stroke();
  523. }
  524. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  525. ctx.lineWidth *= this.networkScaleInv;
  526. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  527. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.options.color.background;
  528. ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius);
  529. ctx.fill();
  530. ctx.stroke();
  531. this._label(ctx, this.label, this.x, this.y);
  532. };
  533. Node.prototype._resizeDatabase = function (ctx) {
  534. if (!this.width) {
  535. var margin = 5;
  536. var textSize = this.getTextSize(ctx);
  537. var size = textSize.width + 2 * margin;
  538. this.width = size;
  539. this.height = size;
  540. // scaling used for clustering
  541. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  542. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  543. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  544. this.growthIndicator = this.width - size;
  545. }
  546. };
  547. Node.prototype._drawDatabase = function (ctx) {
  548. this._resizeDatabase(ctx);
  549. this.left = this.x - this.width / 2;
  550. this.top = this.y - this.height / 2;
  551. var clusterLineWidth = 2.5;
  552. var borderWidth = this.options.borderWidth;
  553. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  554. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  555. // draw the outer border
  556. if (this.clusterSize > 1) {
  557. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  558. ctx.lineWidth *= this.networkScaleInv;
  559. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  560. ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth);
  561. ctx.stroke();
  562. }
  563. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  564. ctx.lineWidth *= this.networkScaleInv;
  565. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  566. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  567. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  568. ctx.fill();
  569. ctx.stroke();
  570. this._label(ctx, this.label, this.x, this.y);
  571. };
  572. Node.prototype._resizeCircle = function (ctx) {
  573. if (!this.width) {
  574. var margin = 5;
  575. var textSize = this.getTextSize(ctx);
  576. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  577. this.options.radius = diameter / 2;
  578. this.width = diameter;
  579. this.height = diameter;
  580. // scaling used for clustering
  581. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  582. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  583. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  584. this.growthIndicator = this.options.radius- 0.5*diameter;
  585. }
  586. };
  587. Node.prototype._drawCircle = function (ctx) {
  588. this._resizeCircle(ctx);
  589. this.left = this.x - this.width / 2;
  590. this.top = this.y - this.height / 2;
  591. var clusterLineWidth = 2.5;
  592. var borderWidth = this.options.borderWidth;
  593. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  594. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  595. // draw the outer border
  596. if (this.clusterSize > 1) {
  597. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  598. ctx.lineWidth *= this.networkScaleInv;
  599. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  600. ctx.circle(this.x, this.y, this.options.radius+2*ctx.lineWidth);
  601. ctx.stroke();
  602. }
  603. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  604. ctx.lineWidth *= this.networkScaleInv;
  605. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  606. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  607. ctx.circle(this.x, this.y, this.options.radius);
  608. ctx.fill();
  609. ctx.stroke();
  610. this._label(ctx, this.label, this.x, this.y);
  611. };
  612. Node.prototype._resizeEllipse = function (ctx) {
  613. if (!this.width) {
  614. var textSize = this.getTextSize(ctx);
  615. this.width = textSize.width * 1.5;
  616. this.height = textSize.height * 2;
  617. if (this.width < this.height) {
  618. this.width = this.height;
  619. }
  620. var defaultSize = this.width;
  621. // scaling used for clustering
  622. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  623. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  624. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  625. this.growthIndicator = this.width - defaultSize;
  626. }
  627. };
  628. Node.prototype._drawEllipse = function (ctx) {
  629. this._resizeEllipse(ctx);
  630. this.left = this.x - this.width / 2;
  631. this.top = this.y - this.height / 2;
  632. var clusterLineWidth = 2.5;
  633. var borderWidth = this.options.borderWidth;
  634. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  635. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  636. // draw the outer border
  637. if (this.clusterSize > 1) {
  638. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  639. ctx.lineWidth *= this.networkScaleInv;
  640. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  641. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  642. ctx.stroke();
  643. }
  644. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  645. ctx.lineWidth *= this.networkScaleInv;
  646. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  647. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  648. ctx.ellipse(this.left, this.top, this.width, this.height);
  649. ctx.fill();
  650. ctx.stroke();
  651. this._label(ctx, this.label, this.x, this.y);
  652. };
  653. Node.prototype._drawDot = function (ctx) {
  654. this._drawShape(ctx, 'circle');
  655. };
  656. Node.prototype._drawTriangle = function (ctx) {
  657. this._drawShape(ctx, 'triangle');
  658. };
  659. Node.prototype._drawTriangleDown = function (ctx) {
  660. this._drawShape(ctx, 'triangleDown');
  661. };
  662. Node.prototype._drawSquare = function (ctx) {
  663. this._drawShape(ctx, 'square');
  664. };
  665. Node.prototype._drawStar = function (ctx) {
  666. this._drawShape(ctx, 'star');
  667. };
  668. Node.prototype._resizeShape = function (ctx) {
  669. if (!this.width) {
  670. this.options.radius= this.baseRadiusValue;
  671. var size = 2 * this.options.radius;
  672. this.width = size;
  673. this.height = size;
  674. // scaling used for clustering
  675. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  676. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  677. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  678. this.growthIndicator = this.width - size;
  679. }
  680. };
  681. Node.prototype._drawShape = function (ctx, shape) {
  682. this._resizeShape(ctx);
  683. this.left = this.x - this.width / 2;
  684. this.top = this.y - this.height / 2;
  685. var clusterLineWidth = 2.5;
  686. var borderWidth = this.options.borderWidth;
  687. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  688. var radiusMultiplier = 2;
  689. // choose draw method depending on the shape
  690. switch (shape) {
  691. case 'dot': radiusMultiplier = 2; break;
  692. case 'square': radiusMultiplier = 2; break;
  693. case 'triangle': radiusMultiplier = 3; break;
  694. case 'triangleDown': radiusMultiplier = 3; break;
  695. case 'star': radiusMultiplier = 4; break;
  696. }
  697. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  698. // draw the outer border
  699. if (this.clusterSize > 1) {
  700. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  701. ctx.lineWidth *= this.networkScaleInv;
  702. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  703. ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth);
  704. ctx.stroke();
  705. }
  706. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  707. ctx.lineWidth *= this.networkScaleInv;
  708. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  709. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  710. ctx[shape](this.x, this.y, this.options.radius);
  711. ctx.fill();
  712. ctx.stroke();
  713. if (this.label) {
  714. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true);
  715. }
  716. };
  717. Node.prototype._resizeText = function (ctx) {
  718. if (!this.width) {
  719. var margin = 5;
  720. var textSize = this.getTextSize(ctx);
  721. this.width = textSize.width + 2 * margin;
  722. this.height = textSize.height + 2 * margin;
  723. // scaling used for clustering
  724. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  725. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  726. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  727. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  728. }
  729. };
  730. Node.prototype._drawText = function (ctx) {
  731. this._resizeText(ctx);
  732. this.left = this.x - this.width / 2;
  733. this.top = this.y - this.height / 2;
  734. this._label(ctx, this.label, this.x, this.y);
  735. };
  736. Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) {
  737. if (text && Number(this.options.fontSize) * this.networkScale > this.fontDrawThreshold) {
  738. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  739. var lines = text.split('\n');
  740. var lineCount = lines.length;
  741. var fontSize = (Number(this.options.fontSize) + 4); // TODO: why is this +4 ?
  742. var yLine = y + (1 - lineCount) / 2 * fontSize;
  743. if (labelUnderNode == true) {
  744. yLine = y + (1 - lineCount) / (2 * fontSize);
  745. }
  746. // font fill from edges now for nodes!
  747. var width = ctx.measureText(lines[0]).width;
  748. for (var i = 1; i < lineCount; i++) {
  749. var lineWidth = ctx.measureText(lines[i]).width;
  750. width = lineWidth > width ? lineWidth : width;
  751. }
  752. var height = this.options.fontSize * lineCount;
  753. var left = x - width / 2;
  754. var top = y - height / 2;
  755. if (baseline == "top") {
  756. top += 0.5 * fontSize;
  757. }
  758. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  759. // create the fontfill background
  760. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  761. ctx.fillStyle = this.options.fontFill;
  762. ctx.fillRect(left, top, width, height);
  763. }
  764. // draw text
  765. ctx.fillStyle = this.options.fontColor || "black";
  766. ctx.textAlign = align || "center";
  767. ctx.textBaseline = baseline || "middle";
  768. for (var i = 0; i < lineCount; i++) {
  769. ctx.fillText(lines[i], x, yLine);
  770. yLine += fontSize;
  771. }
  772. }
  773. };
  774. Node.prototype.getTextSize = function(ctx) {
  775. if (this.label !== undefined) {
  776. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  777. var lines = this.label.split('\n'),
  778. height = (Number(this.options.fontSize) + 4) * lines.length,
  779. width = 0;
  780. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  781. width = Math.max(width, ctx.measureText(lines[i]).width);
  782. }
  783. return {"width": width, "height": height};
  784. }
  785. else {
  786. return {"width": 0, "height": 0};
  787. }
  788. };
  789. /**
  790. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  791. * there is a safety margin of 0.3 * width;
  792. *
  793. * @returns {boolean}
  794. */
  795. Node.prototype.inArea = function() {
  796. if (this.width !== undefined) {
  797. return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x &&
  798. this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x &&
  799. this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y &&
  800. this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y);
  801. }
  802. else {
  803. return true;
  804. }
  805. };
  806. /**
  807. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  808. * @returns {boolean}
  809. */
  810. Node.prototype.inView = function() {
  811. return (this.x >= this.canvasTopLeft.x &&
  812. this.x < this.canvasBottomRight.x &&
  813. this.y >= this.canvasTopLeft.y &&
  814. this.y < this.canvasBottomRight.y);
  815. };
  816. /**
  817. * This allows the zoom level of the network to influence the rendering
  818. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  819. *
  820. * @param scale
  821. * @param canvasTopLeft
  822. * @param canvasBottomRight
  823. */
  824. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  825. this.networkScaleInv = 1.0/scale;
  826. this.networkScale = scale;
  827. this.canvasTopLeft = canvasTopLeft;
  828. this.canvasBottomRight = canvasBottomRight;
  829. };
  830. /**
  831. * This allows the zoom level of the network to influence the rendering
  832. *
  833. * @param scale
  834. */
  835. Node.prototype.setScale = function(scale) {
  836. this.networkScaleInv = 1.0/scale;
  837. this.networkScale = scale;
  838. };
  839. /**
  840. * set the velocity at 0. Is called when this node is contained in another during clustering
  841. */
  842. Node.prototype.clearVelocity = function() {
  843. this.vx = 0;
  844. this.vy = 0;
  845. };
  846. /**
  847. * Basic preservation of (kinectic) energy
  848. *
  849. * @param massBeforeClustering
  850. */
  851. Node.prototype.updateVelocity = function(massBeforeClustering) {
  852. var energyBefore = this.vx * this.vx * massBeforeClustering;
  853. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  854. this.vx = Math.sqrt(energyBefore/this.options.mass);
  855. energyBefore = this.vy * this.vy * massBeforeClustering;
  856. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  857. this.vy = Math.sqrt(energyBefore/this.options.mass);
  858. };
  859. module.exports = Node;