javascript - 设置强制布局中节点的入口

标签 javascript d3.js force-layout

我有一个使用 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+")";
  })
});
});

任何建议都会有帮助。

谢谢。

最佳答案

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

关于javascript - 设置强制布局中节点的入口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23809051/

相关文章:

javascript - Parse.com JQuery 检查数组值是否在解析字段中

javascript - 遍历 JavaScript 对象 - 我错过了什么?

javascript - D3.JS 带点图的工具提示

javascript - JS过滤数组但如果存在反向则不过滤

javascript - 使用 d3.js,如何使用相同的脚本创建具有 3 个数据源的 3 个图表?

javascript - d3js force directed - 在悬停到节点时,突出显示/着色链接节点和链接?

javascript - D3 集群部队布局中的淡入淡出/突出显示

javascript - 我想在我的可移动 div 内创建一个像窗口一样的 div

d3.js - D3 强制布局缩放和平移不起作用

javascript - 如何从使用SWT浏览器从ajax请求获取数据的java脚本函数获取eclipse函数的返回值?