如何为每个圆圈添加文本标签?我的意思是我想旋转这个文本,改变颜色等等?我想获得没有 json 的解决方案,我想从
获取此数据var w = 300,
h = 300;
var data = {
name: "root",
children: [{
name: '1',
size: 70
},
{
name: '2',
size: 90
},
{
name: '3',
size: 70
},
{
name: '4',
size: 40
},
{
name: '5',
size: 70
},
{
name: '6',
size: 20
},
{
name: '7',
size: 70
},
]
}
var canvas = d3.select("#canvas")
.append("svg:svg")
.attr('width', w)
.attr('height', h);
var nodes = d3.layout.pack()
.value(function(d) {
return d.size;
})
.size([w, h])
.nodes(data);
// Get rid of root node
nodes.shift();
canvas.selectAll('circles')
.data(nodes)
.enter().append('svg:circle')
.attr('cx', function(d) {
return d.x;
})
.attr('cy', function(d) {
return d.y;
})
.attr('r', function(d) {
return d.r;
})
.attr('fill', 'white')
.attr('x', 0)
.attr('y', 0)
.attr('width', 6)
.attr('height', 6);
var textLabels = text
.attr("x", function(d) {
return d.cx;
})
.attr("y", function(d) {
return d.cy;
})
.text(function(d) {
return "( " + d.cx + ", " + d.cy + " )";
})
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
#canvas {
width: 300px;
height: 300px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="canvas"></div>
我尝试了很多事情,但没有任何效果..
最佳答案
我不知道你所说的“没有 json”是什么意思,但我修复了你的文本标签。
您在上面的代码中调用了未定义的 text
,我认为您打算将其附加到此处。
您需要为 text
标签创建一个占位符,再次迭代数据,然后附加文本。
canvas.selectAll("text")
.data(nodes)
.enter()
.append("text")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y;
})
.text(function(d) {
return "( " + d.x + ", " + d.y + " )";
})
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "10px")
.attr("color", "black");
关于javascript - 添加文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42548361/