如何在SVG路径上显示文本
所以我在SVG地图上有点,现在我想在其旁边显示文本.这是一个 jsfiddle ,带有2点并显示其ID文本.但是正如您所看到的,没有文本.
So I have points on my SVG map and now I would like to show text next to them. This is a jsfiddle with 2 points and showing their ID text. But as you can see there is no text somehow.
var featureCollection = topojson.feature(topology, topology.objects.testtest);
lines.append("g")
.attr("id", "lines")
.selectAll("path")
.data(featureCollection.features)
.enter().append("path")
.attr("d", path)
.append("text")
.attr("class", "nodetext")
.attr("x", 22)
.attr("y", 4)
.text(function (d) {
return d.properties.id;
});
我在示例旁边加上其他一些文字进行了检查,我已经在此处了.它以相同的方式工作.
And I checked it with some other text beside example I already have here. It's working in the same way.
那么它不适用于路径吗?可以吗?
So does it not work with pathes? Could that be?
正如@liamness所说,您的文字不能是path
的子级,而必须是同级项.但是,由于使用的是路径,并且按常规方式无法对元素进行分组和定位,因此问题会更进一步.在其中方便使用 path.centroid 的位置.它使您可以找到路径的中心并将文本放置在此处:
As @liamness says, your text can't be a child of path
but needs to be a sibling. Your problem goes a little further, though, since you are using a path and you can't group and position the element conventionally. There is where path.centroid comes in handy. It allows you to find the center of you path and position your text there:
var e = lines.append("g")
.attr("id", "lines")
.selectAll("path")
.data(featureCollection.features)
.enter(); // save enter selection
e.append("path") // add path as child of lines g
.attr("d", path);
e.append("text") // add text as child of lines g, sibling of path
.attr("class", "nodetext")
.attr('x', function(d,i){
return path.centroid(d)[0]; // horizontal center of path
})
.attr('y', function(d,i){
return path.centroid(d)[1] + 13; // vertical center of path
})
.attr('text-anchor','middle')
.text(function (d) {
return d.properties.id;
});
更新了小提琴.