【问题标题】:Can't append text to d3.js force layout nodes无法将文本附加到 d3.js 强制布局节点
【发布时间】:2015-05-01 14:06:45
【问题描述】:

目标:将文本附加到 d3 强制布局中的每个节点

BUG:文本附加到对象(我认为,请参见控制台)但未显示在屏幕上

这是jsfiddle

node.append("svg:text")
    .text(function (d) { return d.name; }) // note that this works for
    // storing the name as the id, as seen by selecting that element by
    // it's ID in the CSS (see red-stroked node)
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

如果有任何想法,我将不胜感激。

【问题讨论】:

标签: javascript svg d3.js label force-layout


【解决方案1】:

您不能将 svg 文本添加到 svg 圆圈。您应该首先为每个节点创建一个 svg g 对象(g 代表组),然后为每个 g 元素添加一个圆圈和一个文本,如下代码所示:

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

var circle = node.append("circle")
    .attr("class", "node")
    .attr("id", function (d) { return d.name; })
    .attr("r", 5)
    .style("fill", function (d) {
        return color(d.group);
    });

var label = node.append("svg:text")
    .text(function (d) { return d.name; })
    .style("text-anchor", "middle")
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

当然,tick函数也要相应更新:(还有一点css)

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

label.attr("x", function (d) {
    return d.x;
})
.attr("y", function (d) {
    return d.y - 10;
});

这里是jsfiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多