不可视标签
不可视标签是svg标签中比较核心的部分,扩展了svg的功能。这部分标签不能之前显示在svg视图上,但可以用于定义纹理,和管理标签。
<use> <use> 标签用于复制一个形状. <use>标签是会显示的,显示的形状为href引用中定义的节点的内容,use本身不定义形状的路径。
<svg viewBox="0 0 30 10" xmlns="http://www.w3.org/2000/svg">
<circle id="myCircle" cx="5" cy="5" r="4"/>
<use href="#myCircle" x="10" y="0" fill="blue" />
<use href="#myCircle" x="20" y="0" fill="white" stroke="blue" />
</svg>
<use>的href属性指定所要复制的节点,x属性和y属性是左上角的坐标。另外,还可以指定width和height坐标。
<g> <g>标签用于将多个形状组成一个组(group),方便复用。比如统一设置背景颜色。 准确的说标签是会显示的,不过显示的内容是标签里面子标签的内容.。
<svg width="300" height="100">
<g id="myCircle">
<text x="25" y="20">圆形</text>
<circle cx="50" cy="50" r="20"/>
</g>
<use href="#myCircle" x="100" y="0" fill="blue" />
<use href="#myCircle" x="200" y="0" fill="white" stroke="blue" />
</svg>
<defs> <defs>标签用于自定义形状,它内部的代码不会显示,仅供引用。
<svg width="300" height="100">
<defs>
<g id="myCircle">
<text x="25" y="20">圆形</text>
<circle cx="50" cy="50" r="20"/>
</g>
</defs>
<use href="#myCircle" x="0" y="0" />
<use href="#myCircle" x="100" y="0" fill="blue" />
<use href="#myCircle" x="200" y="0" fill="white" stroke="blue" />
</svg>
<pattern> <pattern>用于定义纹理形状,用于填充。需定义在标签中,子标签可以是任意可视的svg标签。
<svg width="500" height="500">
<defs>
<pattern id="dots" x="0" y="0" width="100" height="100" patternUnits="userSpaceOnUse">
<circle fill="#bee9e8" cx="50" cy="50" r="35" />
</pattern>
</defs>
<rect x="0" y="0" width="100%" height="100%" fill="url(#dots)" />
</svg>
<animate> <animate>标签用于产生动画效果。可以定义类似css类似的动画,作用域svg中形状。
<svg width="500px" height="500px">
<rect x="0" y="0" width="100" height="100" fill="#feac5e">
<animate attributeName="x" from="0" to="500" dur="2s" repeatCount="indefinite" />
</rect>
</svg>
上面代码中,矩形会不断移动,产生动画效果。
<animate>的属性含义如下:
- attributeName:发生动画效果的属性名。
- from:单次动画的初始值。
- to:单次动画的结束值。
- dur:单次动画的持续时间。
- repeatCount:动画的循环模式。
可以在多个属性上面定义动画。
<animate attributeName="x" from="0" to="500" dur="2s" repeatCount="indefinite" />
<animate attributeName="width" to="500" dur="2s" repeatCount="indefinite" />
<animateTransform> <animate>标签对 CSS 的transform属性不起作用,如果需要变形,就要使用<animateTransform>标签。
<svg width="500px" height="500px">
<rect x="250" y="250" width="50" height="50" fill="#4bc0c8">
<animateTransform attributeName="transform" type="rotate" begin="0s" dur="10s" from="0 200 200" to="360 400 400" repeatCount="indefinite" />
</rect>
</svg>
上面代码中,<animateTransform>的效果为旋转(rotate),这时from和to属性值有三个数字,第一个数字是角度值,第二个值和第三个值是旋转中心的坐标。from="0 200 200"表示开始时,角度为0,围绕(200, 200)开始旋转;to="360 400 400"表示结束时,角度为360,围绕(400, 400)旋转。
小结:
svg不可视的标签,大概就是这些。