如何为 SVG 元素中定义的剪切路径设置动画?

How to animate clipping paths defined in SVG elements?

我知道如何为直接在 CSS 中定义的剪辑路径设置动画,但是当剪辑路径被 引用 时,我不知道该怎么做来自 SVG clipPath 元素。

我一直在尝试仅使用 CSS 的简单剪辑路径动画,直到我意识到您不能将 复合路径 定义为剪辑路径直接在那里,所以我求助于 SVG 的 clipPath,它允许定义多个路径。但是然后动画就不行了,就是没有平滑的过渡。

这是我正在尝试的...

HTML

<svg>
    <defs>
        <clipPath id="shape--start">
            <polygon points="0,100 22.222,133.333 8.333,147.222 -13.889,113.889 -47.222,91.667 -33.333,77.778"/>
        </clipPath>
        <clipPath id="shape--end">
            <polygon points="144.444,-44.444 166.667,-11.111 152.778,2.778 130.556,-30.556 97.222,-52.778 111.111,-66.667"/>
        </clipPath>
    </defs>
</svg>

CSS

@keyframes shape {
    0% { clip-path: url(#shape--start) }
    100% { clip-path: url(#shape--end) }
}

为了说明更多,如果我使用类似

的东西

CSS

@keyframes shape {
    0% { clip-path: polygon(-44% 5%, -14% 5%, 15% 95%, -15% 95%) }
    100% { clip-path: polygon(90% 5%, 120% 5%, 149% 95%, 119% 95%) }
}

它按预期工作,但我想将 SVG 用于更复杂的复合路径。

感谢您的宝贵时间和提前的帮助!

您需要使用 animate

为 SVG 本身设置动画

.box {
  width:300px;
  height:200px;
  background:red;
  clip-path: url(#shape--start);
}
<svg width=0 height=0>
    <defs>
        <clipPath id="shape--start">
            <polygon points="0,100 22.222,133.333 8.333,147.222 -13.889,113.889 -47.222,91.667 -33.333,77.778">
            <animate attributeType="XML" attributeName="points" 
            from="0,100 22.222,133.333 8.333,147.222 -13.889,113.889 -47.222,91.667 -33.333,77.778" 
            to="144.444,-44.444 166.667,-11.111 152.778,2.778 130.556,-30.556 97.222,-52.778 111.111,-66.667"
          dur="2s" repeatCount="indefinite"/>
            </polygon>
        </clipPath>
    </defs>
</svg>
<div class="box">

</div>

动画选项使用 animateTransform

.box {
  width:300px;
  height:200px;
  background:red;
  clip-path: url(#shape--start);
}
<svg width="0" height="0">
    <defs>
        <clipPath id="shape--start">
            <polygon points="0,100 22.222,133.333 8.333,147.222 -13.889,113.889 -47.222,91.667 -33.333,77.778">
            <animateTransform attributeType="XML" attributeName="transform" type="translate" 
            values="0,100;144.444,-44.444"
          dur="2s" repeatCount="indefinite"/>
            </polygon>
        </clipPath>
    </defs>
</svg>
<div class="box">

</div>

往返动画

 .box {
  width:300px;
  height:200px;
  background:red;
  clip-path: url(#shape--start);
}
<svg width="0" height="0">
    <defs>
        <clipPath id="shape--start">
            <polygon points="0,100 22.222,133.333 8.333,147.222 -13.889,113.889 -47.222,91.667 -33.333,77.778">
            <animateTransform attributeType="XML" attributeName="transform" type="translate" 
            values="0,100;144.444,-44.444;0,100"
          dur="2s" repeatCount="indefinite"/>
            </polygon>
        </clipPath>
    </defs>
</svg>
<div class="box">

</div>