文本标签在D3 SVG中无法正常显示

时间:2015-05-12 19:43:23

标签: d3.js

我有以下代码在D3中生成一个简单的图...

var width = 800, height = 800;
// force layout setup
var force = d3.layout.force()
        .charge(-200).linkDistance(30).size([width, height]);

// setup svg div
var svg = d3.select("#graph").append("svg")
        .attr("width", "100%").attr("height", "100%")
        .attr("pointer-events", "all");

// load graph (nodes,links) json from /graph endpoint
d3.json("/graph", function(error, graph) {
    if (error) return;

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

    // render relationships as lines
    var link = svg.selectAll(".link")
            .data(graph.links).enter()
            .append("line")
            .attr("class", "link")
            .attr("stroke", "black");

    // render nodes as circles, css-class from label
    var node = svg.selectAll(".node")
            .data(graph.nodes).enter()
            .append("circle")
            .attr("r", 10)
            .call(force.drag);
    // html title attribute for title node-attribute
    node.append("title")
            .text(function (d) { return d.title; })
            .attr("font-family", "sans-serif")
            .attr("font-size", "20px")
            .attr("fill", "black");
    // force feed algo ticks for coordinate computation
    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; });
    });
});

除了我看不到标题外,一切看起来都很棒。如果我查看DOM,我会看到以下内容......

<circle r="10" cx="384.5368115283669" cy="390.4516626058579"><title font-family="sans-serif" font-size="20px" fill="black">My NAme</title></circle>

然而无论我尝试什么,我似乎都看不到标题。我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

这对d3来说无可指责。根据{{​​3}},title是一个描述字符串,在呈现图形时不会呈现。但是,当鼠标指针悬停在元素上时,大多数浏览器都会将标题显示为工具提示。

我已根据您的代码设置了更新的代码段。将鼠标放在红色圆圈上将显示工具提示&#34;我的名字&#34;。

&#13;
&#13;
<svg width="200" height="200">
  <circle r="10" cx="38" cy="39" fill="red">
    <title>My Name</title>
  </circle>
</svg>
&#13;
&#13;
&#13;

要向将要呈现的svg添加文本,请改用<text>元素。

&#13;
&#13;
<svg width="200" height="200">
  <text x="50" y="100">My Text</text>
</svg>
&#13;
&#13;
&#13;