D3: Show network reaching layout, then stop force

守給你的承諾、 提交于 2019-12-11 18:12:40

问题


I'm trying to get my D3 network to freeze after it reaches a nice layout (alpha reaches 0). I want the force to stop completely, even when a node is dragged (the user should be able to rearrange the nodes manually). I think I know how to do the second part of this, by modifying the functions that are called on mousedown and mouseup for the nodes. However, I can't get the original layout and freezing to work.

I've looked at the examples for "static" force layouts, where the network is displayed only after the layout is completed. However, I want the network to display as it's reaching the stable layout. I added this to the end of the function that draws the network:

while (force.alpha() >0.005) {
    force.tick();
}
force.stop();

With this addition, the network doesn't display until it gets to force.stop(). Does anyone know how I can get it to display while it's "ticking"?

EDIT: Here's my implementation of the tick function:

function tick(e) {

console.log(force.alpha());
if (force.alpha() <0.05) {
    force.stop();
}
var h = svgH;

if (e.alpha < 0.05) {
    var q = d3.geom.quadtree(nodes),
    i = 0,
    n = nodes.length;

    while (++i < n) {
        q.visit(collide(nodes[i], e.alpha));
    }
}   


path.attr("d", function(d) {

    // Total difference in x and y from source to target
    diffX = d.target.x - d.source.x;
    diffY = d.target.y - d.source.y;

    // Length of path from center of source node to center of target node
    pathLength = Math.sqrt((diffX * diffX) + (diffY * diffY));

    // x and y distances from center to outside edge of target node
    offsetX = (diffX * d.target.radius) / pathLength;
    offsetY = (diffY * d.target.radius) / pathLength;

    if (d.target.y < d.source.y) {
        var avgY = (d.target.y + d.source.y)/2;

        if (d.target.fixed != true) {
            d.target.y = avgY;
        }
        if (d.source.fixed != true) {
            d.source.y = avgY;
        }
    } 

    return "M" + d.source.x + "," + d.source.y + "L" + (d.target.x - offsetX) + "," + (d.target.y - offsetY);
});

// Keep circles within bounds of screen
var r = 6;
circle.attr("cx", function(d) { return d.x = Math.max(r + d.radius, Math.min(w - r, d.x)); })
        .attr("cy", function(d) {
            return d.y = Math.max(d.radius, Math.min(h - d.radius, d.y));
        });

        text.attr("transform", function(d) {
        return "translate(" + d.x + "," + d.y + ")";
        });
}

回答1:


Check the stop condition in the tick event handler -- this way you can redraw the network on each tick and stop.



来源:https://stackoverflow.com/questions/17243440/d3-show-network-reaching-layout-then-stop-force

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!