SVG 急速入门教程(10.<view>元素)

142 阅读1分钟

上一篇:SVG 视口和用户空间

<view> 元素用于显示同一个 svg 图形的不同区域。

1. 基本语法

<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>
  • <view> 内嵌于 <svg> 中;
  • id 用于引用此 <view>
  • viewBox 定义 <view> 显示 <svg> 的哪块区域;
  • preserveAspectRatio 覆盖 <svg> 的 preserveAspectRatio

2. 举例说明

有以下 SVG 图形:定义了 蓝色、红色、黑色背景的 3 个矩形,并且定义了 3 个 <view> 元素用于分别显示那 3 个矩形:

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

view-3-rects.svg

使用 <img> 引用上图 SVG 中的 <view>

  • 无法通过 svg.id 的方式来引用,必须通过 src="{URL}#{viewId}" 的方式;

我们称 {URL}#{viewId} 为 target fragment 语法。

3. 另一种引用方式

上面的 {URL}#{viewId} 引用方式有一些局限性:我们顶多只能引用3个不同的 <view>。如何在不修改原始 svg 文件的前提下,自定义想要的 <view> 呢?

答案是使用 {URL}#svgView({attributeName}({value})[;...]) 语法:

  • svgView 这是固定的;
  • attributeName 可以是 viewBox/preserveAspectRatio/transform 等;
  • 多个 attributeName 用分号(;)隔开。

使用 <img> 引用上图 SVG 中的 <view>

我们称此种引用方式为 SVG view fragment 语法。

4. 小结

本节介绍了如何使用 <view> 显示同一个 svg 图形的不同区域,下节我们学习使用 transform 对坐标进行变换。

下一篇:变换(transform)