暗黑模式
view 元素
前端教程SVG
<view> 元素用于显示同一个 svg 图形的不同区域。
基本语法
html
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
<view id="blueRect" viewBox="0 0 100 100" preserveAspectRatio="xxx" />
<view id="redRect" viewBox="100 100 100 100" preserveAspectRatio="xxx" />
<view id="blackRect" viewBox="200 200 100 100" preserveAspectRatio="xxx" />
<rect x="0" y="0" width="100" height="100" fill="blue"></rect>
<rect x="100" y="100" width="100" height="100" fill="red"></rect>
<rect x="200" y="200" width="100" height="100" fill="black"></rect>
</svg>1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
<view>内嵌于<svg>中;id:用于引用此<view>;viewBox:定义<view>显示<svg>的哪块区域;preserveAspectRatio:覆盖<svg>的 preserveAspectRatio。
举例说明
有以下 SVG 图形:定义了 蓝色、红色、黑色背景的 3 个矩形,并且定义了 3 个 <view> 元素用于分别显示那 3 个矩形:
html
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="300px" viewBox="0 0 300 300">
<view id="blueRect" viewBox="0 0 100 100" />
<view id="redRect" viewBox="100 100 100 100" />
<view id="blackRect" viewBox="200 200 100 100" />
<rect x="0" y="0" width="100" height="100" fill="blue"></rect>
<rect x="100" y="100" width="100" height="100" fill="red"></rect>
<rect x="200" y="200" width="100" height="100" fill="black"></rect>
</svg>1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
使用 <img> 引用 <view>:
- 无法通过
svg.id的方式来引用,必须通过src="{URL}#{viewId}"的方式;
TIP
我们称 {URL}#{viewId} 为 target fragment 语法。
另一种引用方式
上面的 {URL}#{viewId} 引用方式有一些局限性:我们顶多只能引用3个不同的 <view>。如何在不修改原始 svg 文件的前提下,自定义想要的 <view> 呢?
答案是使用 {URL}#svgView({attributeName}({value})[;...]) 语法:
svgView:这是固定的;attributeName:可以是viewBox/preserveAspectRatio/transform等;- 多个
attributeName用分号(;)隔开。
使用 <img> 引用 <view>:
TIP
我们称此种引用方式为 SVG view fragment 语法。
小结
本节介绍了如何使用 <view> 显示同一个 svg 图形的不同区域,下节我们学习使用 transform 对坐标进行变换。






