Javascript 具有节点和链接的D3js拖动行为

Javascript 具有节点和链接的D3js拖动行为,javascript,d3.js,Javascript,D3.js,我的最终目标是得到类似的东西。因此我使用d3js,但我是一个非常初学者。我尝试了很多力布局,但我认为我不需要任何动画,只需要我可以拖动更新链接的节点。我已经定义了一个有效的拖动行为: var dragListener = d3.behavior.drag() .on("dragstart", function (d) { dragStarted = true; d3.event.sourceEvent.stopPropagation(); })

我的最终目标是得到类似的东西。因此我使用d3js,但我是一个非常初学者。我尝试了很多力布局,但我认为我不需要任何动画,只需要我可以拖动更新链接的节点。我已经定义了一个有效的拖动行为:

var dragListener = d3.behavior.drag()
    .on("dragstart", function (d) {
        dragStarted = true;
        d3.event.sourceEvent.stopPropagation();
    })
    .on("drag", function (d) {
        // update the node position
        var n = d3.select(this);
        n.attr("cx", d.x = d3.event.x);
        n.attr("cy", d.y = d3.event.y);
        update();
    })
    .on("dragend", function (d) {});
我的更新方法是:

function update () {
    force.nodes(nodes)
         .links(links);

    // Update links
    var l = vis.select("#linkG").selectAll("line.link")
               .data(links, function (d) { return d.source.id + "-" + d.target.id; })
               .enter()
               .append("svg:line")
               .attr("class", "link");

    l.style("stroke", "#000")
     .style("stroke-width", 1);

    // Update nodes
    var n = vis.select("#nodeG").selectAll("a")
               .data (nodes, function (d) { return d.id; })
               .enter()
               .append("svg:a").attr("xlink:href", function (d) { return "/user/" + d.id; })
               .append("svg:circle")
               .attr("class", "node")
               .attr("r", function (d) { return d.r; })
               .style("fill", "#454545")
               .style("stroke", "#e7ecef")
               .style("stroke-width", 3)
               .call(dragListener);

    force.on("tick", function () {
        nodes[0].x = WIDTH / 2;
        nodes[0].y = HEIGHT / 2;

        // Tried to update the link positions
        l.attr("x1", function (d) { console.log(d); return d.source.x; }) // HERE
         .attr("y1", function (d) { return d.source.y; })
         .attr("x2", function (d) { return d.target.x; })
         .attr("y2", function (d) { return d.target.y; });

        // Hopefully updates the node positions
        n.attr("cx", function (d) { console.log(d.x); return d.x; })
         .attr("cy", function (d) { return d.y; });
    });
}
我已经在初始化时开始了force布局。语句
console.log(d)
从未触发。数据都很好,html中的所有元素都创建得很好


问题是,链接未显示或更新。有人能帮我得到正确的行为吗?

我终于找到了解决办法(希望如此)。一个很好的帮助是这些堆栈溢出。现在,我可以根据需要正确拖动节点。该点是部队布局的
d.fixed=true
。也许这对其他人有帮助。

对于初学者来说,雄心勃勃!:)我几乎试了整整三天。我向你脱帽致敬!您是否能够在
返回d.x上设置断点就在console.log之后?谢谢!我使用升华文本,我不知道如何设置断点,但通过控制台日志,我看到在拖动方法中,
d.x
是正确的,
force.on tick..
中的
console.log
从未被调用。您可以在chrome f12脚本选项卡的行上放置断点。。因此,当您在浏览器中运行它时,您将点击它(应该点击它)
返回d.source.x