【问题标题】:How to add text to d3.js nodes?如何向 d3.js 节点添加文本?
【发布时间】:2016-11-03 22:58:49
【问题描述】:

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

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

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

下面是代码,我的倒霉做法标注:

<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>

【问题讨论】:

  • 你为什么使用选择器'first-child'和'node.insert'?根据我的理解,您正在尝试向所有节点添加文本?我想您应该在定义样式等的地方添加“.text”。

标签: javascript html d3.js text nodes


【解决方案1】:

如果你查看节点:

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

然后看看你在那之后做了什么:

node.insert("div", ":first-child")
 .append("text")

您会看到问题:您正在尝试将文本附加到圆圈,但这不起作用。除此之外,您不能&lt;div&gt; 或任何其他 HTML 标记附加到 SVG(foreignObject 是另一回事)。

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

var myText = svg.selectAll(".mytext")
                .data(graph.nodes)
                .enter()
                .append("text")
                //the rest of your code

这里是工作插件:https://plnkr.co/edit/UwQfPscQiOg87IEMYtET?p=preview

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多