SVG文本位于矩形上方的奇怪布局

3

我试图将SVG文本(当然是包裹在<text>中)放置在SVG <rect> 上。

我想让它看起来像居中对齐的文字。

但是奇怪的是,它看起来并不像我想象的那样。

它看起来像这样

enter image description here

而我原以为应该是这样的

enter image description here

有什么问题吗?

一开始我以为在<text><rect>xy相等会有用,但实际效果如下图片

enter image description here

我认为在文本中使用y="50%"可以强制文本在中间某处对齐。但是我只能在y="80%"时做到,如您所见。

原始标记在此处

<svg height="500" width="500" class="ng-scope">

  <svg height="50" width="393.703125" y="0">

    <g>
      <rect x="0" y="0" height="50" width="393.703125" style="fill: #A8A8A8">
      </rect>
      <text font-family="Airal" font-size="45" x="0" y="50%" inline-size="200">
        TEST TEXT IN SVG
      </text>
    </g>
  </svg>

</svg>

2个回答

3
y属性默认应用于文本底线,因此文本的y位置和线条、矩形或其他形状的y位置之间存在差异。您可以使用alignment-baseline属性,例如middle,以获得更好的结果。这里是w3c的描述,其中包含许多其他选项。

<svg height="500" width="500" class="ng-scope">

  <svg height="50" width="393.703125" y="0">

    <g>
      <rect x="0" y="0" height="50" width="393.703125" style="fill: #A8A8A8">
      </rect>
      <text font-family="Airal" font-size="45" x="0" y="50%" inline-size="200" alignment-baseline="middle">
        TEST TEXT IN SVG
      </text>
    </g>
  </svg>

</svg>


1
哦,哇,好棒的答案!其实我以前从来没有尝试过使用SVG。还有感谢你提供的链接 :) - DanilGholtsman

2

添加viewBox。虽然我不是SVG专家,只是做了一些工作,但这可能有效。

<svg height="500" width="500" class="ng-scope">

  <svg height="50" width="393.703125" y="0" viewBox="0 0 90 90">

    <g>
      <rect x="0" y="0" height="50" width="393.703125" style="fill: #A8A8A8" >
      </rect>
      <text font-family="Airal" font-size="45" x="0" y="50%" inline-size="200">
        TEST TEXT IN SVG
      </text>
    </g>
  </svg>

</svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接