pixelbeat
pixelbeat

Reputation: 95

Adding new nodes to a clustered force layout

Using the Mike Bostock example for clustered nodes, I'm trying to create a way to push a new node to the flock.

function addNode(){
  nodes.push({
    cluster: 2,
    radius: 5,
    x: Math.cos(3 / 4 * 2 * Math.PI) * 200 + width / 2 + Math.random(),
    y: Math.sin(5 / 4 * 2 * Math.PI) * 200 + height / 2 + Math.random()
  });
  console.log(nodes);
  update();
}

$('button').click(function(){
  addNode();
})

I'm creating new nodes using the same values for cluster and radius but with random values for x & y.

Here is the fiddle, but it's not working as expected.

Upvotes: 2

Views: 963

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

You're almost there, it's just a few small things:

  • You're selecting by "circle.node" in the update function, but you haven't assigned the "node" class to the initial circles.
  • You're using d.size to set the radius of the new circle, but don't set d.size, but d.radius.
  • You're calling .style(...) immediately after .data() and saving the result as the new selection. This messes up the enter and exit selections.

Finally, you didn't include JQuery in your fiddle, so the button doesn't work. Example will all of these issues fixed here.

Upvotes: 2

Related Questions