如何在SVG矩形中放置和居中放置文本 [英] How to place and center text in an SVG rectangle
问题描述
我有以下矩形...
<rect x="0px" y="0px" width="60px" height="20px"/>
我想将小说"一词放在其中.对于其他矩形,svg换行是否保留在其中?对于在水平和垂直居中以及自动换行的形状中插入文本,我似乎找不到任何特别的东西.另外,文本不能离开矩形.
I would like to center the word "Fiction" inside of it. For other rectangles, does svg word wrap to stay within them? I can't seem to find anything specifically about inserting text within shapes that are centered both horizontally and vertically and word wrap. Also, the text can not leave the rectangle.
查看 http://www.w3.org/TR/SVG/text.html# TextElement 示例无济于事,因为文本元素的x和y与矩形的x和y不同.文本元素似乎没有宽度和高度.我不确定这里的数学.
Looking at the http://www.w3.org/TR/SVG/text.html#TextElement example doesn't help since the text element's x and y are different from the rectangle's x and y. There doesn't seem to be width and height for text elements. I am not sure of the math here.
(我的html表无法使用.)
(My html table is just not going to work.)
推荐答案
在SVG中将文本水平和垂直居中的简单解决方案:
An easy solution to center text horizontally and vertically in SVG:
-
将文本的位置设置为要居中的元素的绝对中心:
- 如果是父母,则可以执行
x="50%" y ="50%"
. - 如果是另一个元素,
x
将是该元素的x
+宽度的一半(对于y
类似,但具有高度).
- If it's the parent, you could just do
x="50%" y ="50%"
. - If it's another element,
x
would be thex
of that element + half its width (and similar fory
but with the height).
使用 text-anchor
属性将居中水平值为middle
的文本:
中间
对齐渲染字符,以使生成的渲染文本的几何中间位于当前的初始文本位置.
The rendered characters are aligned such that the geometric middle of the resulting rendered text is at the initial current text position.
使用 dominant-baseline
属性将居中
middle
(或根据您想要的外观,您可能希望执行 central
)
Use the dominant-baseline
property to center the text vertically with the value middle
(or depending on how you want it to look like, you may want to do central
)
这是一个简单的演示:
<svg width="200" height="100">
<rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/>
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TEXT</text>
</svg>
这篇关于如何在SVG矩形中放置和居中放置文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!