SVG.JS 使用现有路径向文本添加文本路径

SVG.JS Adding a Text Path to Text, using an existing path

试图在 SVGJS 中的文本元素上放置一个文本路径,但我想使用现有路径而不是 SVGJS 在我必须更新的 defs 部分中创建一个额外的路径元素。

这样做的原因是我有一个(文本)标签出现在一条线上,可以四处拖动,我希望能够让原生 SVG 执行此操作,而不是必须同时更新元素上的文本路径。

所以目前SVG.JS会这样做

<defs>
  <path id="SvgjsPath0010" d="M0,0L100,100" />
</defs>
....
<g>
  <path id="SvgjsPath1234 d="M0,0L100,100" />
  <text>
    <textPath id="SvgjsTextPath0011" href="#SvgjsPath0010">
      A Label
    </textPath>
  </text>
</g>

我想要实现的是在 SVG.JS 中执行此操作,只需使用上面的 path 元素作为 TextPath...

<g>
  <path id="SvgjsPath1234 d="M0,0L100,100" />
  <text>
    <textPath id="SvgjsTextPath0011" href="#SvgjsPath1234">
      A Label
    </textPath>
  </text>
</g>

我试过传递 Path 对象,但没有成功,而且关于这个的文档有点脆弱。我已经试过了;

var path = mySvgGroup.path('M0,0L100,100');

var line = mySvgGroup.text('A Label');
line.path( path );

但好像不太喜欢。

我认为目前最好的选择是手动构建 Text 元素,但更喜欢更快、更清晰的选项。

有什么建议吗?

在 svg.js v2 中,没有很好的方法来重用 textPaths 的路径。不幸的是,实现不遵循 clip 或 mask 的行为,您可以在其中传递要重用的对象。

此问题已在 svg.js v3 中修复。我们正在努力尽快发布它。但是在那之前你只能使用这个固定版本:

SVG.extend(SVG.Text, {
  path: function(d) {
    // create textPath element
    var path  = new SVG.TextPath
    var track

    if (d instanceof SVG.Path) {
      track = d
    } else {
      track = this.doc().defs().path(d)
    }

    // move lines to textpath
    while (this.node.hasChildNodes())
      path.node.appendChild(this.node.firstChild)

    // add textPath element as child node
    this.node.appendChild(path.node)

    // link textPath to path and add content
    path.attr('href', '#' + track, SVG.xlink)

    return this
})

实际上这个修复非常小,我们可能会将它移植到 v2 :)

现在你可以只传入路径