Skip to content

Instantly share code, notes, and snippets.

@iros
Created April 15, 2016 19:49
Show Gist options
  • Select an option

  • Save iros/b9d2f4bc8401da3339cacae94cf22f7a to your computer and use it in GitHub Desktop.

Select an option

Save iros/b9d2f4bc8401da3339cacae94cf22f7a to your computer and use it in GitHub Desktop.

Revisions

  1. iros created this gist Apr 15, 2016.
    55 changes: 55 additions & 0 deletions force.reqanimframe.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    var force = d3.layout.force()
    .charge(-150)
    .linkDistance(30)
    .size([width, height]);

    d3.json("assets/500nodes.json", function(error, graph) {
    if (error) throw error;

    // Task 2:
    // Connect the force layout to the nodes and links in our dataset
    // and start the simulation
    force
    .nodes(graph.nodes)
    .links(graph.edges)
    .start();

    // Task 3:
    // Render the links connecting the nodes. They should be 'line' elements
    // that have a stroke-width that is the square root of the link 'value'
    // attribute, representing the strength of the relationship. They should bind
    // to the graph edges array.
    var link = svg.selectAll(".link")
    .data(graph.edges)
    .enter()
    .append("line")
    .attr("class", "link")
    .style("stroke-width", function(d) {
    return Math.sqrt(d.value);
    });

    // Create node elements for each node. They are circle elements with a fixed
    // radius of 5. They are colored by their group association and have
    // drag enabled by default.
    var node = svg.selectAll(".node")
    .data(graph.nodes)
    .enter().append("circle")
    .attr("class", "node")
    .attr("r", 5)
    .style("fill", function(d) { return color(d.group); })
    .call(force.drag);

    // with reqAnimframe:
    function animate() {
    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; });
    }

    d3.timer(animate);