Штрих SVG, CSS анимация: не все штрихи движутся в одном направлении - PullRequest
1 голос
/ 04 октября 2019

Анимация ниже довольно проста, или я так думал. Вы заметите, что один из ударов, и только один, начинает двигаться назад. Я не понимаю, почему это так.

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

Спасибо за помощь, оцените любые указатели.

1 Ответ

2 голосов
/ 04 октября 2019

Общая длина пути path1 равна 2000 px

Если вы хотите получить 4 сегмента с 4 равными интервалами, то длина одного штриха будет равна одной восьмой от общей длины: 2000 / 8 = 250 px

В этом случае запись stroke-dasharray = "250, 250"

Анимация достигается путем уменьшения stroke-dashoffset с 2000px до нуля

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