block by mbostock 3355967

Resizable Force Layout

Full Screen

Try opening this example in a new window and resizing it.

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style>

html,
body {
  margin: 0;
  overflow: hidden;
}

.link {
  stroke: #ccc;
}

.node {
  fill: steelblue;
}

</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>

var svg = d3.select("body").append("svg");

var force = d3.layout.force();

d3.json("graph.json", function(error, graph) {
  if (error) throw error;

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .on("tick", tick)
      .start();

  var link = svg.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link");

  var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", 4.5);

  resize();
  d3.select(window).on("resize", resize);

  function tick() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  }

  function resize() {
    width = window.innerWidth, height = window.innerHeight;
    svg.attr("width", width).attr("height", height);
    force.size([width, height]).resume();
  }
});

</script>