svg描边动画原理

1. svg基本图形有7种

矩形 <rect>
圆形 <circle>
椭圆 <ellipse>
线 <line>
折线 <polyline>
多边形 <polygon>
路径 <path>

其中,path可以绘制任意图形

2. svg描边动画原理

svg的描边动画就是利用stroke-dasharray和stroke-dashoffset两个属性值的变化来实现的。

2.1 stroke-dasharray用来画虚线

stroke-dasharray: 实线长度 虚线长度,可以设置多个值,奇数自动重复一遍补成偶数,即 stroke-dasharray: 10 等价于 stroke-dasharray: 10 10

2.2 stroke-dashoffset用来控制虚线的偏移

2.3 描边动画原理

 当stroke-dasharray和stroke-dashoffset都足够大,大于线条的长度,则stroke-dashoffset从固定值变化到0的过程,线条就会从无到伸展到其长度。如果svg线条

为path,则可以实现任意复杂图形的描边动画。

2.4 下面是几个例子

2.4.1 鼠标hover画直线

<svg>
  <line id="line" x1="30" y1="30" x2="300" y2="30" stroke-width="20" stroke="red" stroke-dasharray="300,320"/>
</svg>
#line{
    transition: all 2s;
    stroke-dashoffset: 300;
}
svg:hover #line{
    stroke-dashoffset: 0;
}

2.4.2 环形进度条

<svg  width="200" height="200" viewBox="0 0 200 200">
   <circle id="circle" cx="100" cy="80" r="50"  fill="gray" stroke-width="5" stroke="green" />
</svg>
#circle{
     transition: all 2s;
     stroke-dasharray:314; /*314为环形周长*/
     stroke-dashoffset:314;
}
svg:hover #circle{
    stroke-dashoffset:0;
}

2.4.3 任意图形的描边动画

path {  
  stroke-dasharray: 1000;  
  stroke-dashoffset: 1000;  
  animation: dash 5s linear infinite;  
}  
  
@keyframes dash {  
  to {  
    stroke-dashoffset: 0;  
  }  
}  

2.4.4 矩形虚线框边线滚动效果

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200">
    <rect id="strokedrect" x="0" y="0" width="300" height="200" />
</svg>
@keyframes marchingants {
    to { stroke-dashoffset: 19; }
}
rect#strokedrect {
    stroke: hsl(260, 50%, 90%);
    fill: white;
    stroke-width: 7;
    stroke-dasharray: 10;
    animation: marchingants 1s forwards infinite linear;
}

 

参考:https://justcoding.iteye.com/blog/2226355

          https://segmentfault.com/a/1190000007309718

posted @ 2019-08-15 15:23  全玉  阅读(943)  评论(0编辑  收藏  举报