首页 > 解决方案 > svg animateMotion 结束事件监听器

问题描述

我在我的 html 中有 svg ,其中有一个路径和一个animateMotion沿路径移动的圆圈(带有 )。如何检测何时animationMotion结束以便我可以执行任务?还有我如何重置animationMotion- 即把移动的圆圈带回线的起点。下面是我的 svg html 代码:

<svg id="cc-line" x="0px" y="0px" viewBox="0 -23 150 55" width="150px" height="55px" xml:space="preserve">
      <path fill="#2471A3" d="M0 0 l150 0" stroke="#2471A3" stroke-width="5"/>
      <circle id="cc-line-circle" cx="0" cy="0" r="8" fill="#2471A3">
        <animateMotion id="cc-line-motion" path="M0 0 l150 0"
 			begin= "0s" dur="6.0s" repeatCount="indefinite" rotate="auto" fill="freeze">
      </circle>
    </svg>

标签: javascripthtmlcsssvg

解决方案


将移动的圆圈带回线的起点

您可以通过将关键帧添加到您的<animateMotion>

keyPoints="0;1;0" keyTimes="0;0.5;1" calcMode="linear"

中的三个值keyPoints表示每个关键帧沿线的分数。“0”表示开始,“1”表示结束。

中的三个值keyTimes表示每个关键帧所在的持续时间的分数。“0”是开始,“0.5”是一半,“1”是结束。

如何检测 animationMotion 何时结束以便我可以执行任务?

最好的方法是使用 Dacre 建议的“onrepeat”事件。该事件称为“repeatEvent”

var anim = document.getElementById("cc-line-motion");

var i=0;

anim.addEventListener("repeatEvent", function(evt) {
  console.log("repeat "+(++i));
});
<svg id="cc-line" x="0px" y="0px" viewBox="0 -23 150 55" width="150px" height="55px" xml:space="preserve">
  <path fill="#2471A3" d="M0 0 l150 0" stroke="#2471A3" stroke-width="5"/>
  <circle id="cc-line-circle" cx="0" cy="0" r="8" fill="#2471A3">
    <animateMotion id="cc-line-motion" path="M0 0 l150 0"
 	                 begin="0s" dur="6.0s" repeatCount="indefinite" rotate="auto"
                   keyPoints="0;1;0" keyTimes="0;0.5;1" calcMode="linear"/>
  </circle>
</svg>


推荐阅读