问题描述
开始使用d3.js,我从此示例页面中获取了示例代码,然后尝试以我需要的方式更改它.
Making first steps with d3.js I have taken sample code from this sample page and try to change it the way I need it.
实际上,我想将TEXT添加到彩色节点.他们已经设置了title属性,但是我无法添加非工具提示文本.
Actually I want to add TEXT to the colored nodes. They already have a title property set, but I can't manage to add not-tooltip text.
参考和简介文档对此没有帮助.
Reference and introduction documents did not help on this.
这是代码,我的无穷方法标记为:
Here is the code, my fortuneless approach is marked:
<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>
推荐答案
如果您查看节点:
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
然后看看你做了什么:
node.insert("div", ":first-child")
.append("text")
您会看到问题:您正在尝试将文本追加到圈子中,但这是行不通的.除此之外,您不能将<div>
或任何其他HTML标签附加到SVG(foreignObject
是另一回事).
You'll see the problem: You are trying to append texts to circles, and this doesn't work. Besides that, you can not append <div>
or any other HTML tag to a SVG (foreignObject
is a different story).
所以,这是一个解决方案:
So, this is a solution:
var myText = svg.selectAll(".mytext")
.data(graph.nodes)
.enter()
.append("text")
//the rest of your code
这是工作中的打工者: https://plnkr.co/edit/UwQfPscQiOg87IEMYtET?p=预览
Here is the working plunker: https://plnkr.co/edit/UwQfPscQiOg87IEMYtET?p=preview
这篇关于如何将文本添加到d3.js节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!