【发布时间】: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