d3js move a node without dragging

前端 未结 2 1879
一生所求
一生所求 2021-01-16 14:15

I\'m moving a node in my d3.js graph using the following code:

d3.select(\"#\"+ nodeid).attr(\"x\",x);
d3.select(\"#\"+ nodeid).attr(\"y\",y);
相关标签:
2条回答
  • 2021-01-16 14:34

    I ended up just adding this to the code as well

    d3.select("#"+ nodeid).data([{x: x, y: y}]);
    
    0 讨论(0)
  • 2021-01-16 14:53

    You're updating the DOM element (the graphic), but not the underlying data, and the dragstart event is using the original location that's still stored in the data.

    Try something like this:

    force.setNodeCoords = function (id, x, y) {
        var fnodes = force.nodes();
        fnodes[id].x = x;
        fnodes[id].y = y;
        force.nodes(fnodes);
        svg.selectAll("circle.node")
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; });
    };
    

    (where svg is your SVG or other parent div, and node is the class of your nodes)

    You'll probably also want to update the lines/links!

    0 讨论(0)
提交回复
热议问题