【问题标题】:How to center text in an SVG region如何使 SVG 区域中的文本居中
【发布时间】:2020-08-16 17:11:00
【问题描述】:

我正在尝试使文本在我的 SVG 区域中居中,但没有成功。有没有人知道如何优化这个?

<svg xmlns="http://www.w3.org/2000/svg" aria-label="Usa Mo" viewBox="0 0 70.389999 62.16">
    <g>
       <path tabindex="0" aria-label="Sainte Genevieve" fill="red" id="sainte genevieve" name="Sainte Genevieve" 
             d="m 57.466419,33.749401 
                  2.854,2.605 
                  -1.578,2.754 
                  -0.463,-0.343 
                  -0.441,0.418 
                  -1.953,-1.762 
                  -0.824,-0.796 
                  1.293,-1.417 
                  -0.982,-0.73 
                  1.582,-1.112 
                  0.512,0.383"
       > </path>
       <text font-family="Verdana" font-size="0.75" fill="blue">
           <textPath href="#sainte genevieve" startOffset="50%" text-anchor="middle">Sainte Genevieve</textPath>
       </text>
    </g>
</svg>

【问题讨论】:

  • 也许您需要为文本使用不同的路径。您可以为 sainte 选择一侧,为 genevieve 选择另一侧。这个id="sainte genevieve" 也不是有效的 id
  • @RobertLongson 我做了,但无济于事。
  • @enxaneta 我的目标是使文本居中;你说的两边是什么意思?感谢您注意无效的 ID。文本仍然显示。这将如何影响文本的间距?
  • 您可以编辑您的问题并添加您尝试实现的目标的图像吗?
  • @enxaneta 我没有图纸。我只希望文本位于彩色区域内并且正面朝上。

标签: svg icons vector-icons


【解决方案1】:

OP 正在评论:

我只希望文本位于彩色区域内并且正面朝上。

在这种情况下,您不需要使用 textPath。你需要找到路径的中心。为此,您首先获得路径的边界框:let bb = thePath.getBBox()

接下来你得到路径的中心:

let x = bb.x + bb.width/2;
let y = bb.y + bb.height/2;

最后你将文本的 x 和 y 属性设置为 x 和 y 以确保文本以该点为中心:text-anchor="middle" dominant-baseline="middle"

let bb = thePath.getBBox();
theText.setAttribute("x", bb.x + bb.width/2);
theText.setAttribute("y", bb.y + bb.height/2);
svg{border:1px solid; width:300px}
<svg xmlns="http://www.w3.org/2000/svg" aria-label="Usa Mo"  viewBox="50 30 15 12">
 
       <path id="thePath" aria-label="Sainte Genevieve" fill="red" id="sainte_genevieve" name="Sainte Genevieve" 
             d="m 57.466419,33.749401 
                  2.854,2.605 
                  -1.578,2.754 
                  -0.463,-0.343 
                  -0.441,0.418 
                  -1.953,-1.762 
                  -0.824,-0.796 
                  1.293,-1.417 
                  -0.982,-0.73 
                  1.582,-1.112 
                  0.512,0.383"
       > </path>
       <text id="theText" font-family="Verdana" font-size=".75" fill="blue" text-anchor="middle" dominant-baseline="middle">
            Sainte Genevieve
       </text>
</svg>

观察:我改变了 svg 元素的 viewBox,因为我想让 thePath 居中。你可以把它改回原来的样子。

【讨论】:

    猜你喜欢
    • 2011-04-04
    • 2013-08-10
    • 1970-01-01
    • 2017-12-05
    • 2016-04-29
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多