SVG 急速入门教程(06.绘制文本)

179 阅读1分钟

上一篇:自定义形状(Custom Shapes)

本节我们介绍如何使用 <text> <tspan> <textPath> 元素绘制文本。

1. <text>

<text x="50%" y="120" fill="blue" stroke="red" font-size="24" font-weight="bold" font-family="微软雅黑">
    Hello World 文本 微软雅黑
</text>
  • (x,y) 第一个字的基线坐标
  • fill 文本颜色
  • stroke 文本描边颜色;stroke-width 描边宽度
  • text-anchor 文本锚点,取值:start | middle | end | inherit
  • textLength 文本绘制长度限制(拉伸或压缩文本)
  • lengthAdjust 控制文本是如何被拉伸或压缩到 textLength 的,取值:spacing | spacingAndGlyphs

2. <tspan>

<tspan> 嵌套在 <text> 或 <tspan> 中,对某段文本担当设置坐标和样式。

类似于以下的 HTML 代码,<strong> <em> <span> 把一段文本中的某些文字单独设立样式:

<p><strong></strong><em></em><i></i><span style="color:red"></span></p>

SVG 中使用 <tspan> 达到类似的效果:

<text>
    文字1
    <tspan dx="{{offsetX}}" dx="{{offsetY}}" fill="{{textColor}}">文字2</tspan>
    <tspan x="{{xCoord}}" y="{{yCoord}}" stroke="{{strokeColor}}">文字3
        <tspan ...>文字4</tspan>
    </tspan>
</text>
  • dx dy 坐标偏移
  • x y 完全自定义的坐标
  • fill stroke ... 自定义的样式

<tspan> 不能单独使用 ,只能嵌套在 <text> 或 <tspan> 里。

3. <textPatn>

可以把 <text> 和 <path> 结合起来,让文本沿着 <path> 排版:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">
    <path id="myPath" d="M0,200 a200,200 0 1, 0 400, 0 a200, 200 0 1, 0 -400, 0"></path>
    <text>
        <textPath startOffset="0" href="#myPath">123456789</textPath>
    </text>
</svg>
  • href 被使用的 path id
  • startOffset 路径的起始偏移量

<textPath> 不能单独使用 ,只能嵌套在 <text> 或 <tspan> 里。

关于 href

SVG 1.1 版本中使用 XLink 技术,而从 SVG 2.0 开始废弃了 XLink,采用了 HTML 的链接技术,就是我们熟悉 <a href="xxx" title="xxx" target="_blank"> 中的 href,参考 SVG 2.0 Links

4. 相关 DOM 接口

5. 小结

本节讲解了有关绘制文本的内容,下一节我们讲解在 SVG 里如何绘制图片。

下一篇:绘制图片