如何在 SVG 矩形中放置和居中文本 [英] How to place and center text in an SVG rectangle

查看:27
本文介绍了如何在 SVG 矩形中放置和居中文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下矩形:

我想把小说"这个词居中在它里面.对于其他矩形,SVG 自动换行是否保留在其中?我似乎找不到任何关于在水平和垂直居中以及自动换行的形状中插入文本的具体内容.另外,文字不能离开矩形.

查看 https://www.w3.org/TR/SVG/text.html#TextElement 示例没有帮助,因为文本元素的 x 和 y 与矩形的 x 和 y 不同.文本元素似乎没有宽度和高度.我不确定这里的数学.

(我的 HTML 表格无法正常工作.)

解决方案

在 SVG 中水平和垂直居中文本的简单解决方案:

  1. 将文本的位置设置为要居中的元素的绝对中心:

  • 如果是父级,你可以只做 x=50%";y =50%".
  • 如果它是另一个元素,x 将是该元素的 x + 其宽度的一半(与 y 类似,但高度为).

  1. 使用文本锚 属性将文本水平居中,值为 middle:

<块引用>

渲染的字符对齐,使得生成的渲染文本的几何中间位于初始当前文本位置.

  1. 使用dominant-baseline 属性以使用值 middle 垂直居中文本(或者根据您希望它的外观,您可能想要执行 central)

这是一个简单的演示:

<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>

如果您想将其应用于许多元素,您也可以将其与 CSS 一起使用.例如:

svg 文本{文本锚:中间;显性基线:中间;}

I have the following rectangle:

<rect x="0px" y="0px" width="60px" height="20px"/>

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.

Looking at the https://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.

(My HTML table is just not going to work.)

解决方案

An easy solution to center text horizontally and vertically in SVG:

  1. Set the position of the text to the absolute center of the element in which you want to center it:

  • If it's the parent, you could just do x="50%" y ="50%".
  • If it's another element, x would be the x of that element + half its width (and similar for y but with the height).

  1. Use the text-anchor property to center the text horizontally with the value middle:

middle

The rendered characters are aligned such that the geometric middle of the resulting rendered text is at the initial current text position.

  1. 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)

Here is a simple demo:

<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>

You can also use this with CSS if you want to apply it to many elements. For example:

svg text{
  text-anchor: middle;
  dominant-baseline: middle;
}

这篇关于如何在 SVG 矩形中放置和居中文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆