使用 defs、path 和 textpath 创建一个完整的 SVG xml 在现有的 Snap 文档中创建了一个重复的 DEFS 标签。我做了类似下面的事情来逃避这个问题。总体而言,您的解决方案似乎有效。
var txt = s.text(50,50,"").attr({
stroke: "black",
fill:"none",
fontFamily: "Helvetica Nueue, Helvetica, sans-serif",
fontWeight: "bold"
});
var myFrag = Snap.parse('<path id="MyPath" d="M 50 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100"/>');
var txtpath = Snap.parse('<textPath id="myTextPath" xlink:href="#MyPath">We go up, then we go down, then up again</textPath>');
var defns = s.select('defs');
defns.append(myFrag);
txt.append(txtpath);
console.log("Definitions: -->" + defns.toString());
console.log("Text Element: -->" + txt.toString());
输出:
Definitions: --><defs><radialGradient cx="145" cy="331" r="38"><stop offset="0%" stop-color="#ffffff"/><stop offset="50%" stop-color="#4b4b7b"/><stop offset="100%" stop-color="#444444"/></radialGradient><rect width="10" height="10" class="svg---mgr"/><path id="MyPath" d="M 50 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100"/></defs>
Text Element: --><text x="50" y="50" stroke="#000000" fill="none" style="font-family: 'Helvetica Nueue', Helvetica, sans-serif; font-weight: bold;"><textPath id="myTextPath" xlink:href="#MyPath">We go up, then we go down, then up again</textPath></text>
但是,我不确定这是否是一种非常优雅的方式。我认为应该提供一个 API 来实现这一点。最好像接收一个 textPath 字符串,它在内部做我们上面做的同样的事情。