对于svg.js我写了一个小插件,添加了 textPath 功能。该插件非常简洁:
// textpath plugin
SVG.TextPath = function() {
this.constructor.call(this, SVG.create('textPath'))
}
SVG.TextPath.prototype = new SVG.Element
SVG.extend(SVG.TextPath, {
text: function(text) {
while (this.node.firstChild) this.node.removeChild(this.node.firstChild)
this.node.appendChild(document.createTextNode(text))
return this
}
})
SVG.extend(SVG.Text, {
path: function(d){
var textPath = new SVG.TextPath().text(this.content)
while (this.node.firstChild) this.node.removeChild(this.node.firstChild)
this.track = this.doc().defs().path(d)
this.node.appendChild(textPath.node)
textPath.attr('xlink:href', '#' + this.track)
return this
}
})
创建与 this example on MDN 相同的输出,该插件的使用方法如下:
// example usage
var draw = SVG('canvas').viewbox(0, 0, 1000, 300)
var text = draw.text('We go up, then we go down, then up again')
text.font({ size: 42.5, family: 'Verdana' })
text.path('M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100')
draw.use(text.track).attr({ fill: 'none', 'stroke-width': 1, stroke: '#f09' })
这是动态版本的 fiddle : http://jsfiddle.net/wout/LNuWM/
但这就是出错的地方,因为文本没有渲染。起初我以为我的代码有问题,但是当我从检查器复制 svg 输出并将其粘贴到 svg 文档中时,文本按预期呈现。
这里是静态版本的示例: http://jsfiddle.net/wout/ZbM7K/
这是浏览器故障还是我遗漏了什么?
更新: 现在这个问题已经解决了: http://jsfiddle.net/wout/LNuWM/2/
最佳答案
这似乎是 SVG.js 中的一个错误。由于添加了 XLink 命名空间,SVG 根元素变得困惑:
<svg style="position:relative;overflow:hidden;left:0px;top:0px;"xlink="http://www.w3.org/1999/xlink" ...
---------------------------------------------------------------^
|
--------this should read [SPACE]xmlns:xlink=
关于javascript - 由 JavaScript 生成时 SVG textPath 不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17744164/