【问题标题】:SVG stroke, CSS animation: not all strokes moving in the same directionSVG 笔画、CSS 动画:并非所有笔画都朝同一个方向移动
【发布时间】:2019-10-03 21:24:40
【问题描述】:

下面的动画非常简单,至少我是这么认为的。您会注意到其中一个笔画,而且只有一个,开始向后移动。我不明白为什么会这样。

.container {
  width: 350px;
  height: 350px;
}
#path1 {
  stroke-dasharray: 170;
  animation: animate1 5s infinite linear forwards;
}

@keyframes animate1 {
  50% {
    stroke-dashoffset: -16.4%;
    stroke-dasharray: 0 87.5%;
  }
  100% {
    stroke-dashoffset: -100%;
    stroke-dasharray: 170;
  }
}
<div class="container">
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="100%" height="100%" viewBox="0 0 1000 1000" xml:space="preserve">
        <a xlink:href="#">
            <path id="path2" fill="#000" d="M173,226h400v400H173V226z"/>
            <path id="path1" fill="none" stroke="#000" d="M108,171h500v500H108V171z"/>
        </a>    
    </svg>
</div>

感谢您的帮助,感谢任何指点。

【问题讨论】:

  • 由于您将stroke-dashoffset 表示为百分比,它不再针对path 元素的pathLength 进行解析,而是作为视口的百分比进行解析,因此您的关键帧正在尝试解析不准确地计算并在他们进行时这样做。留下评论,因为我目前没有时间给出适当的解释。

标签: css svg svg-animate


【解决方案1】:

路径path1的总长度为2000 px

如果你想得到4个等间距的4段,那么一个笔划的长度将等于总长度的八分之一:2000 / 8 = 250 px

在这种情况下,写 stroke-dasharray = "250, 250"

动画是通过将stroke-dashoffset2000px减少到零来实现的

.container {
  width: 350px;
  height: 350px;
}
#path1 {
  stroke-dasharray: 250;
  stroke-dashoffset:2000;
  animation: animate1 5s infinite linear forwards;
}

@keyframes animate1 {
  
  100% {
    stroke-dashoffset: 0;
    stroke-dasharray: 250;
  }
}
<div class="container">
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="100%" height="100%" viewBox="0 0 1000 1000" xml:space="preserve">
        <a xlink:href="#">
            <path id="path2" fill="#000" d="M173,226h400v400H173V226z"/>
            <path id="path1" fill="none" stroke="#000" d="M108,171h500v500H108V171z"/>
        </a>    
    </svg>
</div>

SVG 解决方案

<style>
.container {
  width: 350px;
  height: 350px;
}

</style>
<div class="container">
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="100%" height="100%" viewBox="0 0 1000 1000" xml:space="preserve">
        <a xlink:href="#">
            <path id="path2" fill="#000"  d="M173,226h400v400H173V226z"/>
            <path id="path1" fill="none" stroke="#000" stroke-dasharray="250,250" stroke-dashoffset="2000" d="M108,171h500v500H108V171z">
			   <animate
			     attributeName="stroke-dashoffset"
				 from="2000"
				 to="0"
				 dur="5s"
				 repeatCount="indefinite" />
			</path>
        </a>    
    </svg>
</div>

【讨论】:

  • 谢谢亚历山大!这就说得通了。提供 2 个实现来启动真是锦上添花。