我正在尝试在 SVG
圆圈内附加文本,例如 this我的 D3
map 中的示例。我在 SO 上看到了很多类似的问题 - 我用它们来编写下面的代码,但不明白为什么它根本没有出现。
d3.json("https://raw.githubusercontent.com/d3/d3.github.com/master/world-110m.v1.json", function (error, topo) {
if (error) throw error;
gBackground.append("g")
.attr("id", "country")
.selectAll("path")
.data(topojson.feature(topo, topo.objects.countries).features)
.enter().append("path")
.attr("d", path);
gBackground.append("path")
.datum(topojson.mesh(topo, topo.objects.countries, function (a, b) { return a !== b; }))
.attr("id", "country-borders")
.attr("d", path);
console.log("Background Drawn");
var point = gPoints.selectAll("circle")
.data(pointsData)
.enter()
.append("circle")
.attr("cx", function (d) { return d.location[0]; })
.attr("cy", function (d) { return d.location[1]; })
.attr("r", 10)
//Other attributes and mouseovers, etc
var texts = gPoints.selectAll("text")
.data(pointsData)
.enter()
.append("text")
.text(function (d) { return d.performance; });
console.log("Points Drawn");
});
最佳答案
text
没有出现的原因是:您没有指定它需要出现的任何位置。
对于圆圈,您将提供 cx
和 cy
,但对于文本则不提供任何内容。
更好的方法是创建这样的组:
var elem = gPoints.selectAll("g .myCircleText").data(pointsData)
/*Create and place the "blocks" containing the circle and the text */
var elemEnter = elem.enter()
.append("g")
.classed("myCircleText", true) //add a class to the group
.attr("transform", function(d){return "translate("+d.location[0]+","+ d.location[1]+")"})
如上所示给组一个翻译(这样你就不需要给组一个 cx 和 cy 组被翻译到需要的点)。
现在像这样在组内画圈:
/*Create the circle for each block */
var circle = elemEnter.append("circle")
.attr("r", 10 )
.attr("stroke","black")
.attr("fill", "white")
现在在组内制作文本
/* Create the text for each block */
elemEnter.append("text")
.attr("dx", function(d){return -20})//so that it comes 20 pixel from center.
.text(function(d){return d.performance})
关于javascript - D3 中的 SVG 圆圈内的文本不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411365/