forcegraph: set size based on diameter

This commit is contained in:
Nils Schneider 2015-04-01 18:21:54 +02:00
parent b7ce336227
commit 534f7bbed4

View File

@ -11,6 +11,10 @@ define(["d3"], function (d3) {
var LINK_DISTANCE = 70 var LINK_DISTANCE = 70
function graphDiameter(nodes) {
return Math.sqrt(nodes.length / Math.PI) * LINK_DISTANCE
}
function savePositions() { function savePositions() {
if (!localStorageTest()) if (!localStorageTest())
return return
@ -65,9 +69,17 @@ define(["d3"], function (d3) {
"scale(" + scale + ")") "scale(" + scale + ")")
} }
function getSize() {
var sidebarWidth = sidebar.getWidth()
var width = el.offsetWidth - sidebarWidth
var height = el.offsetHeight
return [width, height]
}
function panzoomTo(a, b) { function panzoomTo(a, b) {
var sidebarWidth = sidebar.getWidth() var sidebarWidth = sidebar.getWidth()
var size = force.size() var size = getSize()
var targetWidth = Math.max(1, b[0] - a[0]) var targetWidth = Math.max(1, b[0] - a[0])
var targetHeight = Math.max(1, b[1] - a[1]) var targetHeight = Math.max(1, b[1] - a[1])
@ -85,14 +97,6 @@ define(["d3"], function (d3) {
animatePanzoom(translate, scale) animatePanzoom(translate, scale)
} }
function resize() {
var sidebarWidth = sidebar.getWidth()
var width = el.offsetWidth - sidebarWidth
var height = el.offsetHeight
force.size([width, height])
}
function tickEvent() { function tickEvent() {
link.selectAll("line") link.selectAll("line")
.attr("x1", function(d) { return d.source.x }) .attr("x1", function(d) { return d.source.x })
@ -140,8 +144,6 @@ define(["d3"], function (d3) {
.on("drag", dragmove) .on("drag", dragmove)
.on("dragend", dragend) .on("dragend", dragend)
window.addEventListener("resize", resize)
self.setData = function (data) { self.setData = function (data) {
var nodePositions = {} var nodePositions = {}
@ -227,24 +229,19 @@ define(["d3"], function (d3) {
node.selectAll("title").text(nodeName) node.selectAll("title").text(nodeName)
var diameter = graphDiameter(nodes)
force.nodes(nodes) force.nodes(nodes)
.links(links) .links(links)
.size([diameter, diameter])
resize() .start()
force.start()
} }
self.resetView = function () { self.resetView = function () {
node.classed("highlight", false) node.classed("highlight", false)
link.classed("highlight", false) link.classed("highlight", false)
var size = force.size() panzoomTo([0, 0], 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])
doAnimation = true doAnimation = true
} }
@ -281,8 +278,6 @@ define(["d3"], function (d3) {
} }
self.destroy = function () { self.destroy = function () {
window.removeEventListener("resize", resize)
force.stop() force.stop()
node.remove() node.remove()
link.remove() link.remove()