From 534f7bbed4ca7b1971d928479ae714ef70273df0 Mon Sep 17 00:00:00 2001 From: Nils Schneider Date: Wed, 1 Apr 2015 18:21:54 +0200 Subject: [PATCH] forcegraph: set size based on diameter --- lib/forcegraph.js | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/lib/forcegraph.js b/lib/forcegraph.js index a2b525e..9835df2 100644 --- a/lib/forcegraph.js +++ b/lib/forcegraph.js @@ -11,6 +11,10 @@ define(["d3"], function (d3) { var LINK_DISTANCE = 70 + function graphDiameter(nodes) { + return Math.sqrt(nodes.length / Math.PI) * LINK_DISTANCE + } + function savePositions() { if (!localStorageTest()) return @@ -65,9 +69,17 @@ define(["d3"], function (d3) { "scale(" + scale + ")") } + function getSize() { + var sidebarWidth = sidebar.getWidth() + var width = el.offsetWidth - sidebarWidth + var height = el.offsetHeight + + return [width, height] + } + function panzoomTo(a, b) { var sidebarWidth = sidebar.getWidth() - var size = force.size() + var size = getSize() var targetWidth = Math.max(1, b[0] - a[0]) var targetHeight = Math.max(1, b[1] - a[1]) @@ -85,14 +97,6 @@ define(["d3"], function (d3) { animatePanzoom(translate, scale) } - function resize() { - var sidebarWidth = sidebar.getWidth() - var width = el.offsetWidth - sidebarWidth - var height = el.offsetHeight - - force.size([width, height]) - } - function tickEvent() { link.selectAll("line") .attr("x1", function(d) { return d.source.x }) @@ -140,8 +144,6 @@ define(["d3"], function (d3) { .on("drag", dragmove) .on("dragend", dragend) - window.addEventListener("resize", resize) - self.setData = function (data) { var nodePositions = {} @@ -227,24 +229,19 @@ define(["d3"], function (d3) { node.selectAll("title").text(nodeName) + var diameter = graphDiameter(nodes) + force.nodes(nodes) .links(links) - - resize() - - force.start() + .size([diameter, diameter]) + .start() } self.resetView = function () { node.classed("highlight", false) link.classed("highlight", false) - var size = force.size() - var diameter = Math.sqrt(nodes.length / Math.PI) * LINK_DISTANCE - var x = (size[0] - diameter) / 2 - var y = (size[1] - diameter) / 2 - - panzoomTo([x, y], [x + diameter, y + diameter]) + panzoomTo([0, 0], force.size()) doAnimation = true } @@ -281,8 +278,6 @@ define(["d3"], function (d3) { } self.destroy = function () { - window.removeEventListener("resize", resize) - force.stop() node.remove() link.remove()