【问题标题】:How to show text on a SVG path如何在 SVG 路径上显示文本
【发布时间】:2015-05-17 17:41:44
【问题描述】:

所以我的 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 的例子。它的工作方式相同。

那么它不适用于路径吗?会这样吗?

【问题讨论】:

    标签: javascript jquery css svg d3.js


    【解决方案1】:

    正如@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

    【讨论】:

    • 哇,这个效果立竿见影,完美无缺,而且非常直接。惊人的。非常感谢,正是我想要的。
    【解决方案2】:

    “文本”元素不能是“路径”元素的子元素,它应该是兄弟元素。如果它们相关并且需要相应地定位,则将它们分组。

    【讨论】:

    • 你能给我一个关于如何更改svg代码的例子吗?或者结构应该如何?我不完全确定如何解决。
    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多