涉及的基础标签与属性
svg标签
- width,height : 画布宽高
- xmlns:声明命名空间,防止来自不同技术的元素发生冲突
- viewBox:指定视口位置和大小(左上角的横坐标和纵坐标,视口宽高)
- stroke:定义 svg 元素的描边颜色,例如线条、文本等描边颜色
- stroke-width:定义 svg 元素的描边宽度
- stroke-opacity:定义 svg 元素的描边透明度
- fill:定义 svg 元素的填充颜色
- fill-opacity:定义 svg 元素的填充透明度
- transform:定义 svg 元素的变换
path 标签
- stroke-dasharray:控制图案描边路径的样式
- stroke-dashoffset:虚线在原路径下的偏移量
- d:指定一系列绘制的命令,命令后面接坐标
d常用命令:
M(移动绘制点到某坐标)
L(绘制一条直线)
H(绘制一条水平线)
V(绘制一条竖线)
Q(绘制一条二次贝塞尔曲线)
C(绘制一条三次贝塞尔曲线)
Z(闭合)
所有命令均允许小写字母。大写表示绝对定位,小写表示相对定位。
从坐标(120, 0)绘制一条直线到坐标(65,200),然后再从(65,200)绘制直线到坐标(225,200)
,最后闭合回到(150, 0)
<path d="M120 0 L65 200 L225 200 Z" />
g 标签
g:用于将多个形状捆绑一个组(group),在 g 标签上定义的属性,会被其所有的子元素继承,添加到g元素上的变换也会应用到其所有的子元素上
<g fill="red">
// 下面的圆都会被填充为红色
<circle cx="15" cy="15" r="10" id="c1"/>
<circle cx="30" cy="30" r="15" id="c2"/>
</g>
image 标签
image:用于插入图片,width 和 height 属性指定图片大小,xmlns:xlink属性指定图片 url
<image xlink:href="assets/home/logo.jpg" width="30" height="30"/>
animateMotion
animateMotion:用于定义元素如何沿运动路径移动
注意:为了复用一个已经定义的路径,就有必要使用一个
- repeatCount:动画运行次数,值为“indefinite”时,无限次运行动画
- xlink:href:指定关联元素的id(需要做动画的元素id)
- path:此属性定义运动的路径()
- dur:动画持续时长
- begin:动画开始时间
- rotate:应用于沿路径动画的元素的旋转,通常是使其指向动画的方向,auto(自动根据轨迹调整好角度)、none(默认,固定角度)
- mpath : mapth是animateMotion子元素,提供了引用外部
元素作为运动路径的定义的能力。 - fill:“freeze” | "remove(默认值)"设置了动画结束后元素的状态。freeze表示动画结束后元素停留在动画的最后状态。remove代表动画结束以后元素回到动画前的状态
路径动画
css方式
利用offset-path画出元素运动路径,然后用 offset-distance 控制元素在路径上的运动距离从 0% 到100%(反过来运动就是100% 到 0%)
html:
<div class="icon-box2">
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<path d="M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" />
</svg>
<div class="icon2"></div>
</div>
css:
.icon-box2 {
background-color: pink;
position: relative;
svg {
path {
stroke: #000;
fill: none;
stroke-width: 2;
}
}
.icon2 {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: red;
position: absolute; //开启定位,配合偏移路径
top: 0;
left: 0;
offset-path: path("M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80"); //元素运动路径
offset-distance: 10%; //初始偏移位置百分比
animation: identifier2 2s linear infinite;
}
}
@keyframes identifier2 {
0% {
offset-distance: -10%;
}
100% {
offset-distance: 100%;
}
}
animateMotion方式
animateMotion定义了一个元素如何沿着运动路径进行移动
利用animateMotion的dur设置动画执行时间,fill指定动画结束后的状态,repeatCount设置动画执行次数,再使用mpath的xlink.href指定元素运动的路径id即可
<div class="icon-box3">
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<path
id="p1-line1"
d="M242.87.22S191.77,63,.68,116.75"
transform="translate(-0.14 1.05)"
style="
fill: none;
stroke-miterlimit: 10;
stroke-width: 4px;
stroke: url(#linear-gradient);
"
/>
<image
x="-20px"
y="-3px"
xlink:href="@/assets/images/fire/point-cost.png"
style="width: 40px; height: 6px"
>
//设置动画持续时间为2.2,rotate自动调节旋转角度,循环次数为indefinite
<animateMotion dur="2.2s" rotate="auto" repeatCount="indefinite">
//引用外部的path路径作为图片的运动路径
<mpath xlink:href="#p1-line1"></mpath>
</animateMotion>
</image>
</svg>
</div>