如何向d3.js节点添加文本?​​

时间:2016-07-01 13:40:06

标签: javascript html d3.js text nodes

使用d3.js迈出第一步我从this sample page获取了示例代码并尝试按照我需要的方式更改它。

实际上我想将TEXT添加到彩色节点。他们已经拥有了title属性集,但我无法添加非工具提示文本。

参考和介绍文件对此没有帮助。

这是代码,我的无辜方法标记为:

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var width = 960,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

    //d3.select("body").transition()
    //.style("background-color", "black");

d3.json("miserables1.json", function(error, graph) {
  if (error) throw error;

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

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

  var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("class", "node")
      //.attr("r", 20)
      .attr("r",  function(d) { return d.radius; }) 
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag);

  node.append("title")
      .text(function(d) { return d.name; });

// -----> my approach to add text to the nodes:
  node.insert("div", ":first-child")
     .append("text")
     .style("fill", "#0000ff")
     .attr("width", "10")
     .attr("height", "10")
     .text(function(d) { return d.name; });
// -----> end of fortuneless approach.

  force.on("tick", function() {
    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; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });
});

</script>

1 个答案:

答案 0 :(得分:3)

如果你看一下节点:

<div class="container">
<div class="col-md-3">
  <p>First column</p>
  </div>
<div class="col-md-3">
  <p>Second column</p>
  </div>
<div class="col-md-3">
  <p>Third column</p>
  </div>
<div class="col-md-3">
  <p>Fourth column</p>
  </div>
</div>

看看你之后做了什么:

var node = svg.selectAll(".node")
  .data(graph.nodes)
.enter().append("circle")

您会看到问题:您正在尝试将文字附加到圈子中,但这并不起作用。除此之外,您无法node.insert("div", ":first-child") .append("text") 或任何其他HTML标记附加到SVG(<div>是另一回事。)

所以,这是一个解决方案:

foreignObject

以下是工作人员:https://plnkr.co/edit/UwQfPscQiOg87IEMYtET?p=preview