【问题标题】:Set the entry of a node in force layout在强制布局中设置节点的入口
【发布时间】:2014-05-22 14:00:36
【问题描述】:

我有一个使用 d3.js 构建的强制布局,节点以 15 秒的间隔进入。当节点进入时,它们从任何随机方向进入,然后在中心定居。我希望节点总是从左上角(0,0)进入,然后去中心定居。

that.force = d3.layout.force()
    .charge(-8.6)
    .linkDistance(2)
    .size([600, 600]);

that.svg = d3.select(that.selector).append("svg")
    .attr("width", that.width)
    .attr("height", that.height);

d3.json("data/tweets.json", function(error, graph) {
  that.graph = graph;
setInterval(function () {
  d3.json("data/tweets.json", function(error, graph) {
    that.graph = graph;
    that.render();
  });
},15000);

that.force
    .nodes(that.graph.nodes)
    .links(that.graph.links)
    .start(0);


that.nodes = that.svg.selectAll("g")
  .data(that.graph.nodes)
  .enter()
  .append("g")
  .call(that.force.drag);


that.nodes
    .append("rect")
    .attr("class", "node")
    .attr("width", that.rectw)
    .attr("height", that.recth)
    .style("fill","white")
    .style("stroke", function(d) { return d.COLOR; })
    .style("stroke-width", "1px")

that.nodes.append("title")
    .text(function(d) { return d.SCREEN_NAME; });

that.nodes.append("image")
    .attr("class", "node-image")
    .attr("transform", "translate(1,1)")
    .attr("xlink:href", function(d) { return "img/"+d.PROFILE_PIC;})
    .attr("height", that.rectw-2 + "px")
    .attr("width", that.recth-2 + "px");

that.link = that.svg.selectAll(".link")
    .data(that.graph.links)
    .enter()
    .append("line")
    .attr("class", "link")
    .style("stroke-width", function(d) { return Math.sqrt(d.value); });

that.force.on("tick", function() {
  that.link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

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

任何建议都会有所帮助。

谢谢。

【问题讨论】:

  • 你能把你的代码贴出来让我们梳理一下吗?

标签: javascript d3.js force-layout


【解决方案1】:

您可以通过设置数据的xy 属性,在将它们赋予强制布局之前预先设置节点的位置。因此,在您的情况下,您只需将所有节点的 xy 初始化为 0。

【讨论】:

  • 所以我需要将我的数据从 {"nodes":[{"name":"abc"}],"links":[]} 更改为 {"nodes":[{"名称":"abc","x":0,"y":0}],"链接":[]}
  • 您可以这样做,也可以在加载 JSON 并设置这些属性后循环遍历您的节点。
  • 那行得通。再次感谢。是否可以为从 0,0 到中心的节点创建曲线路径而不是线性路径?
  • 在将节点插入强制布局之前,您必须修改强制布局的工作方式或执行到中心的路径。这些选项都不是特别容易。
  • 我能在网上找到任何符合这个特殊要求的例子吗
猜你喜欢
  • 2014-08-01
  • 2016-08-15
  • 2018-02-01
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多