问题
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.
回答1:
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 setd.size
, butd.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.
来源:https://stackoverflow.com/questions/22712913/adding-new-nodes-to-a-clustered-force-layout