文本处理
<text> 是 SVG 中用于绘制文本的基本元素,它允许在 SVG 图形中添加可编辑、可选择和可样式化的文本内容。
文本基础
基本语法
xml
<text x="起始x坐标" y="起始y坐标">文本内容</text>示例
html
<svg width="400" height="100">
<text x="50" y="50" font-family="Arial" font-size="24" fill="blue">
SVG 文本示例
</text>
</svg>文本定位
文本定位属性
| 属性 | 描述 | 取值 | 默认值 |
|---|---|---|---|
x | 文本基线起点的 x 坐标 | 数值(像素) | 0 |
y | 文本基线起点的 y 坐标 | 数值(像素) | 0 |
dx | 相对于 x的水平偏移量 | 数值(像素) | 0 |
dy | 相对于 y的垂直偏移量 | 数值(像素) | 0 |
text-anchor | 文本水平对齐方式 | "start"、"middle"、"end" | "start" |
dominant-baseline | 文本垂直对齐方式 | "auto"、"middle"、"central" 等 | "alphabetic" |
对齐示例
html
<svg width="400" height="200">
<!-- 左对齐文本 -->
<text x="50" y="50">左对齐文本</text>
<!-- 居中对齐文本 -->
<text x="200" y="100" text-anchor="middle">居中对齐文本</text>
<!-- 右对齐文本 -->
<text x="350" y="150" text-anchor="end">右对齐文本</text>
</svg>文本样式
文本样式属性
| 属性 | 描述 | 取值 | 默认值 |
|---|---|---|---|
font-family | 字体族 | 字体名称或通用字体族 | "serif" |
font-size | 字体大小 | 数值(像素)或关键字 | "medium" |
font-weight | 字体粗细 | "normal"、"bold" 或数值 | "normal" |
font-style | 字体样式 | "normal"、"italic"、"oblique" | "normal" |
fill | 文本填充颜色 | 颜色值 | "black" |
stroke | 文本描边颜色 | 颜色值 | "none" |
text-decoration | 文本装饰 | "none"、"underline" 等 | "none" |
样式示例
html
<svg width="400" height="300">
<!-- 加粗文本 -->
<text x="50" y="50" font-weight="bold">加粗文本</text>
<!-- 斜体文本 -->
<text x="50" y="100" font-style="italic">斜体文本</text>
<!-- 带描边文本 -->
<text x="50" y="150" fill="red" stroke="black" stroke-width="1">
带描边文本
</text>
</svg>文本路径
使用 <textPath> 元素可以让文本沿着路径排列。
基本示例
html
<svg width="400" height="300">
<defs>
<path id="curvePath" d="M50,150 Q150,50 250,150 T350,150"/>
</defs>
<text font-family="Arial" font-size="16" fill="blue">
<textPath href="#curvePath">
这是沿曲线排列的文本
</textPath>
</text>
</svg>startOffset 属性
使用 startOffset 控制文本在路径上的起始位置。
html
<textPath href="#curvePath" startOffset="50%">
从路径中间开始
</textPath>多行文本
使用 <tspan> 元素创建多行文本。
基本示例
html
<svg width="400" height="200">
<text x="50" y="50" font-family="Arial" font-size="16">
第一行文本
<tspan x="50" dy="25">第二行文本</tspan>
<tspan x="50" dy="25">第三行文本</tspan>
</text>
</svg>tspan 属性
| 属性 | 描述 |
|---|---|
x | 新的 x 坐标 |
y | 新的 y 坐标 |
dx | 相对于前一个文本的水平偏移 |
dy | 相对于前一个文本的垂直偏移 |
实际应用
标签
html
<svg width="200" height="50">
<rect x="0" y="0" width="200" height="50" fill="#4285F4"/>
<text x="100" y="30" text-anchor="middle" fill="white" font-family="Arial" font-size="16">
Button
</text>
</svg>图表标签
html
<svg width="400" height="300">
<!-- X 轴标签 -->
<text x="50" y="280" text-anchor="middle">Jan</text>
<text x="150" y="280" text-anchor="middle">Feb</text>
<text x="250" y="280" text-anchor="middle">Mar</text>
<!-- Y 轴标签 -->
<text x="30" y="250" text-anchor="end">0</text>
<text x="30" y="200" text-anchor="end">50</text>
<text x="30" y="150" text-anchor="end">100</text>
</svg>