如何使用 CSS 为 SVG 路径设置动画

在最近的教程中,我创建了一堆复选框,其中一个具有平滑线动画:

而这一切都可以通过 CSS 来完成。SVG 元素如下所示:

    <svg id="one" width="10em" height="10em" viewBox="115 140 70 70">
        <path fill="none" stroke-linecap="round" class="path" stroke="white" stroke-width="4" d="M173 196 L172 196.33333333333334 L169.8 197.2 L164.71428571428572 197.71428571428572 L161.5 197.875 L156.125 198 L150 197.625 L143.5 196.75 L136.75 195.125 L130.875 192.75 L125.75 189.875 L121.875 186.25 L119.125 181.875 L118.125 176.875 L118.625 171.875 L120.375 167 L123.25 162.5 L127.125 158.625 L131.875 155.25 L137.5 152.625 L143.5 151.125 L149.5 151.125 L155.5 152.375 L161.25 154.5 L166.5 157.5 L171 161.125 L174.75 165.375 L177.625 170.25 L180 175.125 L181.375 179.625 L181.875 183.625 L181.5 187.25 L180.75 190.375 L179.5 193 L178 195 L176.375 196.375 L174.75 197.375 L173.375 198.125 L172 198.83333333333334 L171 199 L170.5 199" />
    </svg>

CSS是这样的:

    svg {
        stroke-dasharray: 1000;
        stroke-dashoffset: 1000;
        pointer-events: none;
    }
    #one {
        animation: firstAnimation 2s linear forwards infinite;
    }
    @keyframes firstAnimation {
        to {
            stroke-dashoffset: 0;
        }
    }

那么它是怎样工作的?stroke-dasharray指的是虚线的宽度和线条的白色部分,stroke-dashoffset指的是虚线的起点。因此,当我们将两者都设置为 1000 时,我们的起点是 1000,超出了我们的行尾,然后破折号的长度为 1000 个单位,超过了行的长度。

当我们将 dashoffset 设置为 0 时,dash 会向上移动,导致线条再次可见。如果我们希望它只运行一次,我们只需要删除infiniteCSS 动画行上的指示器。

不同的偏移量

为了更好地说明这一点,这里的 dasharray 为 10,dashoffset 为 0:

并且 dashoffset 为 10:

最后,使用 50 的 dashoffset 和 dasharray,然后是一个不同的动画过程:

下面是它的 CSS 代码:

    svg {
        animation: secondAnimation 2s linear forwards infinite;
    }
    @keyframes secondAnimation {
        0% {
            stroke-dasharray: 20;
            stroke-dashoffset: 20;
        }
        30% {
            stroke-dasharray: 20;
            stroke-dashoffset: 200;
        }
        50% {
            stroke-dasharray: 60;
            stroke-dashoffset: 400;
        }
        80% {
            stroke-dasharray: 30;
            stroke-dashoffset: 200;
        }
        100% {
            stroke-dasharray: 20;
            stroke-dashoffset: 20;
        }
    }