svg 文本居中异常

svg text-centering anomaly

我需要设置 SVG 参数文本锚点:"middle" 用于吉他和弦图表生成器的一组以小圆圈为中心的单字符 tspan 元素:请参阅 http://chordography.blogspot.co.uk/

当我将 svg 代码粘贴到浏览器:Chrome、IE、Firefox、Opera、Safari 或 Open Office Writer 中时,字符位于中心左侧,最后一个 tspan 元素除外,正确居中。最后一个总是可以的,即使我重新排列 tspan。在大多数情况下,该问题可能并不明显,但在此应用程序中却很突出。

这里,剧情变厚了。当我使用 JavaScript 将 svg 代码直接插入 DOM 时,就像 Chordography 中的正常情况一样,所有 tspan 元素都正确居中。还有一个转折点;当我在 Blogger 中粘贴代码时,它也正确居中,如 http://chordography.blogspot.co.uk/p/blog-page_58.html.

所示

这是从 XMLSerializer 派生的相关部分的代码,显示了圆圈和插图的位置 'labels'。只有最后的“1”和页脚中的最后一个 'A' 正确居中。

<g class="dots">
   <circle cx="62.1" cy="73.6" r="9.6"/>
   <circle cx="85.1" cy="128.8" r="9.6"/>
   <circle cx="108.1" cy="128.8" r="9.6"/>
   <circle cx="131.1" cy="128.8" r="9.6"/>
   <circle cx="154.1" cy="73.6" r="9.6"/>
</g>
<g text-anchor="middle" class="text">
   <text class="labels">
      <tspan x="62.1" y="79.2">1</tspan>
      <tspan x="85.1" y="134.4">2</tspan>
      <tspan x="108.1" y="134.4">3</tspan>
      <tspan x="131.1" y="134.4">4</tspan>
      <tspan x="154.1" y="79.2">1</tspan>
   </text>
   <text class="footer">
      <tspan x="39.1" y="189.6"> </tspan>
      <tspan x="62.1" y="189.6">D</tspan>
      <tspan x="85.1" y="189.6">A</tspan>
      <tspan x="108.1" y="189.6">D</tspan>
      <tspan x="131.1" y="189.6">F♯</tspan>
      <tspan x="154.1" y="189.6">A</tspan>
   </text>
</g>

有点奇怪;任何想法任何人。

如果您将 'text-anchor="middle"' 添加到每个 tspan,您将使它们居中(您还必须 删除 'tspans' 之间的 space , 否则额外的 space 将被视为第一行的一部分,它们将不会完全居中)。

space 很可能是您遇到此问题的原因。

tspan 看起来像这样...

<tspan text-anchor="middle" x="56.5" y="72">1</tspan><tspan
text-anchor="middle" x="77.5" y="122">2</tspan><tspan
text-anchor="middle" x="98.5" y="122">3</tspan><tspan
text-anchor="middle" x="119.5" y="122">4</tspan><tspan
text-anchor="middle" x="140.5" y="72">1</tspan>

参考 jsFiddle:http://jsfiddle.net/rfornal/0u5wmevm/

通常我会对所有不需要的字符进行正则表达式,然后将字符串读取为数组,例如:

var badStr = 'xx,1p23,4 "5'; // string with errors
var newStr = str.replace(/[^x\d]/g,''); // outputs: x12345
console.log(newstr[1]); // debug, outputs: 1