javascript - 使用JavaScript复制CSS或SMIL动画

标签 javascript animation svg stroke-dasharray

SMIL动画以及使用CSS设置SVG元素的动画为not suported on IE 11

为了给我的SVG设置动画,我想使用JavaScript,更改stroke-dashoffset属性。这是我的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>





我知道如何使用style.strokeDashoffset更改属性。

问题是:如何制作动画,以使其在需要时准确地更改属性?

因此,从上面的示例代码中:我希望将strokeDashoffset属性在时间0更改为20 20,在以下位置更改为:0.5的-120,在时间1更改为:-240(动画将无限期地工作)。我尝试以离散的方式进行操作,但这显然不是我所需要的,因为动画需要连续进行。

最佳答案

您可以使用setInterval()函数。


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


并尝试将动画属性传达为间隔的数学函数。

希望这可以帮助

关于javascript - 使用JavaScript复制CSS或SMIL动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57911896/

相关文章:

javascript - CSS 突出显示选定的按钮

javascript - 将输入字段焦点上的标签设置为完全不透明

javascript - 如何使用 svg 生成六边形的随机位置?

javascript - htmlUnit getPage 中的 NaN 值

javascript - TypeError : n is undefined in D3. js,试图复制分层边缘捆绑

javascript - 自动选择并收集数组中的复选框值

javascript - 仅重新加载 iframe 的一部分

c# - Silverlight 中的 Spritesheet

android - 如何在 Android 中的 View 上应用缓动动画功能

javascript - 使用 snap.svg 沿 svg 路径对对象进行动画制作和定向