如何在 SVG 路径上显示文本

How to show text on a SVG path

所以我的 SVG 地图上有一些点,现在我想 在它们旁边显示文本。这是一个 jsfiddle,有 2 个点并显示他们的 ID 文本。但是正如您所见,不知何故没有文字。

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;
  });

除了例子之外,我还用其他一些文本检查了它,我已经有了 here。它的工作方式相同。

所以它不适用于路径吗?可以吗?

'text' 元素不能是 'path' 元素的子元素,它应该是兄弟元素。如果它们相关并且需要相应定位,请将它们分组。

正如@liamness 所说,您的文本不能是 path 的子文本,但必须是兄弟文本。但是,您的问题更进一步,因为您使用的是路径并且您不能按常规对元素进行分组和定位。这就是 path.centroid 派上用场的地方。它允许您找到路径的中心并将文本放置在那里:

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;
    });

已更新 fiddle