简体   繁体   English

使用JavaScript复制CSS或SMIL动画

[英]Replicate CSS or SMIL animation using JavaScript

SMIL animations, as well as animating SVG elements using CSS, is not suported on IE 11 . 在IE 11上没有支持 SMIL动画,以及使用CSS动画SVG元素。

To animate my SVG, I would like to use JavaScript, changing the stroke-dashoffset attribute. 要动画我的SVG,我想使用JavaScript,更改stroke-dashoffset属性。 This is how my SVG looks like: 这就是我的SVG的样子:

  <svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px" viewBox="0 0 70 70" > <rect width="70px" height="70px" stroke="gray" stroke-width="20" fill="none" /> <rect width="70" class="animate" height="70" stroke="yellow" stroke-width="20" fill="none" stroke-dasharray="120"> <!-- A part that I want to replicate with JavaScript --> <animate attributeName="stroke-dashoffset" calcMode="linear" values="20 20;-120;-240" keyTimes="0;0.5;1" dur="1" begin="0s" repeatCount="indefinite" /> </rect> </svg> 

I know how that the attribute can be changed using style.strokeDashoffset . 我知道如何使用style.strokeDashoffset更改属性。

The question is: how do I make my animation so that it changes the attribute exactly at the time I want it to? 问题是:如何制作动画,以便在我想要的时候准确地更改属性?

So from the example code above: I want the strokeDashoffset property to be changed to 20 20 at time 0, to: -120 at 0.5 and: -240 at time 1 (the animation will work idenfinitely). 所以从上面的示例代码:我希望在时间0将strokeDashoffset属性更改为20 20 ,在0.5时更改为-120 ,在时间1更改为: -240 (动画将无限期地工作)。 I tried doing it in a discrete manner but that's obviously not what I need here, as the animation needs to be continuous. 我尝试以离散的方式进行,但这显然不是我需要的,因为动画需要连续。

You may use setInterval() function. 您可以使用setInterval()函数。

let timer = setInterval(function() { if (animation complete) clearInterval(timer); else keep changing the values}, time);

And try conveying your animation property as a mathematical function of the interval. 并尝试将您的动画属性作为间隔的数学函数传达。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM