全面介绍SVG文本处理技术,包括文本元素、字体属性、文本对齐和文本路径。掌握SVG文本绑制的核心技术。 SVG提供了强大的文本处理能力,不仅可以绑制基本文字,还支持文本路径、文本装饰等高级效果。
SVG文本相关的核心元素:
| 元素 | 说明 |
|---|---|
| text | 基本文本元素 |
| tspan | 文本片段,用于样式分段 |
| textPath | 沿路径排列文本 |
使用text元素绑制文字,通过x和y属性定位文本基线。
<text x="150" y="40" text-anchor="middle" font-size="24" fill="#3498db">SVG 文本示例</text>
<text x="150" y="80" text-anchor="middle" font-size="16" fill="#666">支持中文和英文</text>
<text x="150" y="110" text-anchor="middle" font-size="14" fill="#e74c3c">Text in SVG</text>
tspan元素可以在text内部创建不同样式的文本片段。
<text x="150" y="50" text-anchor="middle" font-size="20">
<tspan fill="#3498db">蓝色</tspan>
<tspan fill="#e74c3c">红色</tspan>
<tspan fill="#2ecc71">绿色</tspan>
</text>
<text x="150" y="85" text-anchor="middle" font-size="16">
<tspan font-weight="bold">粗体</tspan>
<tspan font-style="italic">斜体</tspan>
<tspan text-decoration="underline">下划线</tspan>
</text>
textPath让文本沿着指定的路径排列,创造独特的文字效果。
<defs>
<path id="curve" d="M 30,100 Q 150,20 270,100" fill="none"/>
</defs>
<text font-size="16" fill="#3498db">
<textPath href="#curve">
文本沿着曲线路径排列展示效果
</textPath>
</text>
SVG支持常见的CSS字体属性:
| 属性 | 说明 |
|---|---|
| font-family | 字体族 |
| font-size | 字体大小 |
| font-weight | 字体粗细 |
| font-style | 字体样式 |
| text-decoration | 文本装饰 |
<text x="30" y="30" font-family="Arial" font-size="16" fill="#333">Arial 字体</text>
<text x="30" y="60" font-family="Georgia" font-size="16" fill="#333">Georgia 字体</text>
<text x="30" y="90" font-weight="bold" font-size="16" fill="#333">粗体文字</text>
<text x="30" y="120" font-style="italic" font-size="16" fill="#333">斜体文字</text>
text-anchor属性控制文本的水平对齐方式。
<line x1="150" y1="20" x2="150" y2="130" stroke="#e74c3c" stroke-width="1" stroke-dasharray="5,5"/>
<text x="150" y="50" text-anchor="start" font-size="14" fill="#3498db">start 对齐</text>
<text x="150" y="80" text-anchor="middle" font-size="14" fill="#2ecc71">middle 对齐</text>
<text x="150" y="110" text-anchor="end" font-size="14" fill="#f39c12">end 对齐</text>
<rect x="30" y="30" width="80" height="40" rx="5" fill="#3498db"/>
<text x="70" y="55" text-anchor="middle" fill="white" font-size="14">标签一</text>
<rect x="120" y="30" width="80" height="40" rx="5" fill="#e74c3c"/>
<text x="160" y="55" text-anchor="middle" fill="white" font-size="14">标签二</text>
<rect x="210" y="30" width="80" height="40" rx="5" fill="#2ecc71"/>
<text x="250" y="55" text-anchor="middle" fill="white" font-size="14">标签三</text>
<circle cx="80" cy="60" r="40" fill="#3498db"/>
<text x="80" y="65" text-anchor="middle" fill="white" font-size="16">开始</text>
<circle cx="160" cy="60" r="40" fill="#e74c3c"/>
<text x="160" y="65" text-anchor="middle" fill="white" font-size="16">暂停</text>
<circle cx="240" cy="60" r="40" fill="#95a5a6"/>
<text x="240" y="65" text-anchor="middle" fill="white" font-size="16">停止</text>