如何将线条更改为虚线并且仍然有动画?我尝试了很多东西,但我无法弄清楚:
svg {
width: 100%;
height: auto;
}
.path {
fill: none;
stroke: #4CAF50; /* Green color for the success path */
stroke-width: 2;
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: dash 5s linear forwards;
}
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
<svg viewBox="0 0 100 50">
<path class="path" d="M0,25
Q25,10 50,25
Q75,40 100,25"/>
</svg>
假设您的路径长 100 像素。您可以制作一个
stroke-dasharray
,其中有 100 像素的虚线图案,后跟 100 像素(或更多)的间隙,例如:
16 5 16 5 16 5 16 5 16 101
^-- 100px pattern ---^ ^-- At least 100px gap
如果您从
stroke-dashoffset
为 100 开始,您只会看到差距,即什么也看不到。如果您随后慢慢地将偏移量设置为 0,虚线图案将从左侧移入。
在这种情况下,告诉浏览器假设路径也是给定长度,而不是计算其实际长度会更容易。我们可以使用
pathLength
属性来做到这一点。
svg {
width: 100%;
height: auto;
}
.path {
fill: none;
stroke: #4CAF50;
/* Green color for the success path */
stroke-width: 2;
stroke-dasharray: 16 5 16 5 16 5 16 5 16 101;
stroke-dashoffset: 100;
animation: dash 2s linear forwards;
}
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
<svg viewBox="0 0 100 50">
<path class="path" pathLength="100"
d="M0,25 Q25,10 50,25 Q75,40 100,25" />
</svg>