gpt4 book ai didi

javascript - 动态添加节点到 d3.js 强制有向图

转载 作者:行者123 更新时间:2023-11-29 18:18:54 30 4
gpt4 key购买 nike

我在将节点动态添加到 d3.js 力定向图时遇到问题,我想知道这里是否有人可以阐明这个主题。

我遇到的问题是我希望 tick 函数转换图表上的所有 节点,而不仅仅是新添加的节点。

下面是我用来添加节点和处理转换的函数:

// Function to handle tick event
function tick() {
tick_path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" +
d.source.x + "," +
d.source.y + "L" +
d.target.x + "," +
d.target.y;
});

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


/**
* Append nodes to graph.
*/
function addNodes2Graph(){

// define the nodes
// selection will return none in the first insert
// enter() removes duplicates (assigning nodes = nodes.enter() returns only the non-duplicates)
var nodes = viz.selectAll(".node")
.data(g_nodes)
.enter().append("g")
.on("click", nodeClick)
.call(force.drag);

// From here on, only non-duplicates are left
nodes
.append("circle")
.attr("r", 12)
.attr("class", "node");

nodes.append("svg:image")
.attr("class", "circle")
.attr("xlink:href", "img/computer.svg")
.attr("x", "-8px")
.attr("y", "-8px")
.attr("width", "16px")
.attr("height", "16px");

// add the text
nodes.append("text")
.attr("x", 12)
.attr("dy", ".35em")
.text(function(d) { return d.ip; });


return nodes;
}

// Execution (snippet)

// Add new nodes
tick_node = addNodes2Graph();
// Add new paths
tick_path = addPaths2Graph();


// Restart graph
force
.nodes(g_nodes) // g_nodes is an array which stores unique nodes
.links(g_edges) // g_edges stores unique edges
.size([width, height])
.gravity(0.05)
.charge(-700)
.friction(0.3)
.linkDistance(150)
.on("tick", tick)
.start();

我认为问题是我只得到从 addNodes2Graph 返回的非重复结果,然后我在 tick 函数中使用它,但我不确定如何在不添加重复节点的情况下实现这一点到图表。

目前,它要么在图表上添加重复元素,要么只转换 tick 上的新节点。

非常感谢您的提前帮助。

最佳答案

看起来您只是将节点添加到 DOM,而不是强制布局。回顾一下,这是将节点添加到强制布局所需执行的操作。

  • 将元素添加到强制布局用于其节点的数组中。这需要是您最初传入的相同的数组,即如果您想要平滑的行为,您不能创建一个新数组并传递它。修改 force.nodes() 应该可以正常工作。
  • 对链接执行相同的操作。
  • 使用带有新数据的 .data().enter() 添加新的 DOM 元素。
  • 不需要更改 tick 函数,因为添加节点和 DOM 元素是在别处完成的。

添加新节点/链接后,您需要再次调用 force.start() 以将其考虑在内。

关于javascript - 动态添加节点到 d3.js 强制有向图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20698991/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com