Moving fixed nodes in D3

微笑、不失礼 提交于 2020-01-11 02:32:25

问题


I have nodes in a D3 force-directed layout that are set to .fixed = true. If I set the .x or .y values, the nodes themselves don't move to their new position.

Here's my function:

function fixNode(idArray, locationX, locationY) {
    for ( x = 0; x < idArray.length; x++ ) {
        for ( y = 0; y < nodes.length; y++ ) {
            if (nodes[y].id == idArray[x]) {
                nodes[y].fixed = true;
                nodes[y].x = 50;
                nodes[y].y = 50;
                break;
            }
        }
    }
}

UPDATE 1:

Here is the working function based on Jason's advice:

function fixNode(idArray, locationX, locationY) {
    for ( x = 0; x < idArray.length; x++ ) {
        for ( y = 0; y < nodes.length; y++ ) {
            if (nodes[y].id == idArray[x]) {
                nodes[y].fixed = true;
                nodes[y].x = 50;
                nodes[y].y = 50;
                nodes[y].px = 50;
                nodes[y].py = 50;
                break;
            }
        }
    }
    tick();
}

回答1:


The force-directed layout is decoupled from the actual rendering. Normally you have a tick handler, which updates the attributes of your SVG elements for every "tick" of the layout algorithm (the nice thing about the decoupling is you render to a <canvas> instead, or something else).

So to answer your question, you simply need to call this handler directly in order to update the attributes of your SVG elements. For example, your code might look like this:

var node = …; // append circle elements

var force = d3.layout.force()
    .nodes(…)
    .links(…)
    .on("tick", tick)
    .start();

function tick() {
  // Update positions of circle elements.
  node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
}

So you could simply call tick() at any point and update the element positions.

You might be tempted to call force.tick(), but this is meant to be used as a synchronous alternative to force.start(): you can call it repeatedly and each call executes a step of the layout algorithm. However, there is an internal alpha variable used to control the simulated annealing used internally, and once the layout has "cooled", this variable will be 0 and further calls to force.tick() will have no effect. (Admittedly it might be nice if force.tick() always fired a tick event regardless of cooling, but that is not the current behaviour).

As you correctly noted in the comments, if you manually set d.x and d.y, you should also set d.px and d.py with the same values if you want the node to remain in a certain position.



来源:https://stackoverflow.com/questions/10502877/moving-fixed-nodes-in-d3

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