{T}

文本处理

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

参考资源