如何为SVG元素定义的剪辑路径创建动画效果?

5
我知道如何在CSS中直接定义剪辑路径并进行动画,但是我不知道当剪辑路径来自SVG的clipPath元素时该怎么做。
我一直在尝试使用CSS进行简单的clip-path动画,直到我意识到无法直接将复合路径作为clip-path定义,因此我转向了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来处理更复杂的复合路径。

非常感谢您的时间和任何帮助!

2个回答

4

您需要使用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>


3

使用 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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接