谁能给我一个如何在 SVG 中垂直居中多行文本的示例?我用谷歌搜索,看到很多对对齐基线和主导基线e 的引用,但没有具体的例子供我查看。
例如,在下面的 SVG 中,TEXT 元素被其左上角锁定。文本在该 y 位置之后开始出现。如果我希望文本均匀分布在 y 位置的上方和下方,我需要做什么?
<text x="110" y="50" dy="0">
<tspan dy="0em" x="110" style="font-weight: bold; fill: rgb(74, 76, 77);">
<tspan x="110" dy="0em">This is my long quotation that will now wrap</tspan>
<tspan x="110" dy="1.1em">over multiple lines, maybe even two lines!</tspan>
<tspan x="110" dy="1.1em">Isn't that amazing?</tspan>
</tspan>
<tspan dy="1.5em" x="110" style="font-style: italic;">
Speaker, Speaker Description
</tspan>
</text>
Run Code Online (Sandbox Code Playgroud)
(我通过 D3 生成这个,如果有帮助的话)
您无法真正使用 SVG 实现自动居中。SVG 没有适当的自动布局。
但是,您可以使用dy
,就像您正在做的那样,相对于基线定位文本。记住dy
也可以是负数。
<svg width="400" height="150">
<line x1="110" y1="50" x2="400" y2="50" stroke="red"/>
<text x="110" y="50">
<tspan x="110" dy="-0.8em">This is my long quotation that will now wrap</tspan>
<tspan x="110" dy="1.1em">over multiple lines, maybe even two lines!</tspan>
<tspan x="110" dy="1.1em">Isn't that amazing?</tspan>
</text>
</svg>
Run Code Online (Sandbox Code Playgroud)
您可以做的另一件事是使用<foreignObject>
元素将 HTML 嵌入到 SVG 中。显然,这只适用于浏览器。