HTML5 中的可缩放矢量图形(SVG)- 文本和 SVG
 
- UID
- 1066743
|

HTML5 中的可缩放矢量图形(SVG)- 文本和 SVG
文本和 SVG除了基本形状,还可以使用 SVG 生成文本,如清单 17 所示。
清单 17. 使用 SVG 创建文本1
2
3
| <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<text x="0" y="15" fill="red">I love SVG</text>
</svg>
|
清单 17 中的代码会生成图 17 中的图形。
图 17. SVG 文本 此示例使用了一个 text 元素来创建句子 I love SVG。当使用 text 元素时,要显示的实际文本在开始和结束 text 元素之间。
您可以沿多个轴,以及甚至沿多条路径显示文本。清单 18 沿一条弧形路径显示文本。
清单 18. 沿一条弧形路径创建文本1
2
3
4
5
6
7
8
9
| <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<path id="path1" d="M75,20 a1,1 0 0,0 100,0"/>
</defs>
<text x="10" y="100" style="fill:red;">
<textPath xlink:href="#path1">I love SVG I love SVG</textPath>
</text>
</svg>
|
清单 18 中的代码会生成图 18 中的图形。
图 18. 一个弧形路径上的文本 在此示例中,向根 SVG 标记添加了一个额外的 XML 命名空间 xlink。用户显示文本的弧形路径在 def 元素内创建,所以该路径不会在图形中实际渲染出来。要显示的文本嵌套在一个 textPath 元素内,该元素使用 xlink 命名空间引用想要的路径的 id。
与其他 SVG 图形一样,也可以向文本应用过滤器和渐变。清单 19 向一些文本应用了一个过滤器和一种渐变。
清单 19. 创建具有过滤器和渐变的文本1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<radialGradient id="grad1" cx="50%" cy="50%"
r="50%" fx="50%" fy="50%">
<stop offset="0%"
style="stop-color:red; stop-opacity:0"/>
<stop offset="100%"
style="stop-color:rgb(0,0,0);stop-opacity:1"/>
</radialGradient>
<filter id="f1" x="0" y="0"
width="200%" height="200%">
<feOffset result="offOut"
in="SourceAlpha" dx="20" dy="20"/>
<feGaussianBlur result="blurOut"
in="offOut" stdDeviation="10"/>
<feBlend in="SourceGraphic"
in2="blurOut" mode="normal"/>
</filter>
</defs>
<text x="10" y="100" style="fill:url(#grad1); font-size: 30px;"
filter="url(#f1)">
I love SVG I love SVG
</text>
</svg>
|
中的代码会生成图 19 中的图形。
图 19. 具有过滤器和渐变的文本 |
|
|
|
|
|