如何在SVG区域中居中显示文本



我试图将文本置于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>

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,因为我想把Path放在中心。你可以把它改回原来的样子。

最新更新