【问题标题】:Restart SVG animation sequence from Javascript从 Javascript 重新启动 SVG 动画序列
【发布时间】:2022-10-19 05:09:48
【问题描述】:

我正在尝试从 Javascript 重新启动 SVG 动画序列。下面的重新启动按钮将破坏 SVG 动画序列。如何重新启动/重置整个序列?

document.getElementById("button").addEventListener("click", function() {
  document.getElementById("fore").beginElement();
});
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 150">
  <path id="track" fill="none" stroke="#000000" stroke-width="1" stroke-dasharray="10,10" d="M 50 100 L 950 50"/>
  <path id="plane" d="M-10 -10 L10 0L-10 10z" fill="red" />

  <animateMotion xlink:href="#plane" 
    id="fore" 
    begin="0s;back.end" 
    dur="2s" 
    fill="freeze" 
    repeatCount="1" 
    rotate="auto" 
    keyPoints="0;1" 
    keyTimes="0;1"
   ><mpath xlink:href="#track" /></animateMotion>
  
  <animateMotion xlink:href="#plane" 
    id="back" 
    begin="fore.end"  
    dur="2s" 
    fill="freeze" 
    repeatCount="1" 
    rotate="auto-reverse" 
    keyPoints="1;0" 
    keyTimes="0;1"
   ><mpath xlink:href="#track" /></animateMotion>
</svg>

<button id="button">RESTART</button>

【问题讨论】:

    标签: javascript animation svg sequence svg-animate


    【解决方案1】:

    您可以在整个 svg 元素上使用 setCurrentTime。我在 svg 节点中添加了一个 svgEl 的 id,然后当单击 rest 时,我们执行以下操作:

    document.getElementById('svgEl').setCurrentTime(0);
    

    看看这个:

    document.getElementById("button").addEventListener("click", function() {
      document.getElementById('svgEl').setCurrentTime(0);
    });
    <svg id="svgEl" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 150">
      <path id="track" fill="none" stroke="#000000" stroke-width="1" stroke-dasharray="10,10" d="M 50 100 L 950 50"/>
      <path id="plane" d="M-10 -10 L10 0L-10 10z" fill="red" />
    
      <animateMotion xlink:href="#plane" 
        id="fore" 
        begin="0s;back.end" 
        dur="2s" 
        fill="freeze" 
        repeatCount="1" 
        rotate="auto" 
        keyPoints="0;1" 
        keyTimes="0;1"
        restart="always"
       ><mpath xlink:href="#track" /></animateMotion>
      
      <animateMotion xlink:href="#plane" 
        id="back" 
        begin="fore.end"  
        dur="2s" 
        fill="freeze" 
        repeatCount="1" 
        rotate="auto-reverse" 
        keyPoints="1;0" 
        keyTimes="0;1"
        restart="always"
       ><mpath xlink:href="#track" /></animateMotion>
    </svg>
    
    <button id="button">RESTART</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2017-04-28
      • 2013-10-11
      • 2011-03-12
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多