单击冻结svg动画



我有一个svg代码,它可以生成3个改变颜色的矩形。我想通过点击这3个矩形中的任何一个来冻结它们,但我是svg的新手,我不知道如何做到这一点。我尝试过使用javascript,但没有成功。有什么想法吗?

<svg width="500" height="500" onclick="freezing()">
<rect x="10" y="20" width="90" height="60">
<animate id="a1" attributeName="fill" from="red" to="blue" dur="3s" fill="freeze"  />
</rect>
<rect x="10" y="120" width="90" height="60">
<animate id="a2" attributeName="fill" from="blue" to="yellow" dur="3s" fill="freeze"  />
</rect>
<rect x="10" y="220" width="90" height="60">
<animate id="a3" attributeName="fill" from="yellow" to="green" dur="3s" fill="freeze" />
</rect>
</svg>

您可以使用SVGSVGElement#pauseAnimations方法来暂停在该元素内运行的SMIL动画。要继续,您可以调用unpauseAnimations()

const svg = document.querySelector("svg");
svg.onclick = (evt) => {
if (svg.animationsPaused()) {
svg.unpauseAnimations();
}
else {
svg.pauseAnimations();
}
};
<svg width="500" height="500" >
<rect x="10" y="20" width="90" height="60">
<animate id="a1" attributeName="fill" from="red" to="blue" dur="3s" fill="freeze"  />
</rect>
<rect x="10" y="120" width="90" height="60">
<animate id="a2" attributeName="fill" from="blue" to="yellow" dur="3s" fill="freeze"  />
</rect>
<rect x="10" y="220" width="90" height="60">
<animate id="a3" attributeName="fill" from="yellow" to="green" dur="3s" fill="freeze" />
</rect>
</svg>

将SVG中的SMIL动画与JavaScript结合起来确实很困难。在这里,我用JavaScript中的Animation对象替换了animate元素。动画对象有不同的方法,如play((、pause((和cancel((。

通过调用Element.getAnimations((,您可以获取一个元素上的所有动画。它是一个数组,因此您需要对其进行迭代并暂停所有(在本例中只有一个(动画。

let timingoptions = {
duration: 3000,
fill: 'forwards'
};
document.querySelector('rect:nth-child(1)').animate([
{fill: 'red'},
{fill: 'blue'}
], timingoptions);
document.querySelector('rect:nth-child(2)').animate([
{fill: 'blue'},
{fill: 'yellow'}
], timingoptions);
document.querySelector('rect:nth-child(3)').animate([
{fill: 'yellow'},
{fill: 'green'}
], timingoptions);
document.querySelector('svg').addEventListener('click', e => {
e.target.getAnimations().forEach(animation => animation.pause());
});
<svg width="500" height="500">
<rect x="10" y="20" width="90" height="60"/>
<rect x="10" y="120" width="90" height="60"/>
<rect x="10" y="220" width="90" height="60"/>
</svg>

最新更新