SVG触发动画与事件

时间:2011-12-10 10:11:31

标签: javascript events animation svg

如何触发svg animate元素以通过javascript开始使用任意事件进行动画制作?我想象begin="mySpecialEvent"之类的东西,之后我可以发送mySpecialEvent并且动画将开始(或者如果它已经播放则再次开始)。

2 个答案:

答案 0 :(得分:48)

这是一篇涵盖您所需内容的文章:
<击> http://dev.opera.com/articles/view/advanced-svg-animation-techniques/

修改链接已删除。存档副本:

简而言之:

  1. 使用<animation>创建begin="indefinite",这样它就不会将动画视为文档加载时的开头。您可以通过JavaScript或原始SVG源执行此操作。

  2. 准备动画启动时,在SVGAnimationElement实例(<animate>元素)上调用beginElement()。对于您的用例,请在准备好时使用标准addEventListener()回调来调用此方法,例如。

    myAnimationElement.addEventListener('mySpecialEvent',function(){
      myAnimationElement.beginElement();
    },false);
    

答案 1 :(得分:2)

开始制作SVG动画:

在没有JavaScript的情况下,在动画元素上使用begin attribute =“ id.event”(不带“ on”前缀)的“ event-value”类型;或

<svg xmlns="http://www.w3.org/2000/svg" width="600px" height="400px">
  <rect x="10" y="10" width="100" height="100">
    <animate attributeName="x" begin="go.click" dur="2s" from="10" to="300" fill="freeze" />
  </rect>
</svg>

<button id="go">Go</button>

(W3C 2018,“ SVG动画级别2,编辑者的草稿”,https://svgwg.org/specs/animations/),“控制动画时间的属性”,“开始”属性,“事件值”值类型,https://svgwg.org/specs/animations/#TimingAttributes

通过javascript,将动画元素的begin属性设置为“不确定”;并从脚本中调用beginElement();

function go () {
  var elements = document.getElementsByTagName("animate");
  for (var i = 0; i < elements.length; i++) {
    elements[i].beginElement();
  }
}

<svg xmlns="http://www.w3.org/2000/svg" width="600px" height="400px">
  <rect x="10" y="10" width="100" height="100">
    <!-- begin="indefinite" allows us to start the animation from script -->
    <animate attributeName="x" begin="indefinite" dur="2s" from="10" to="300" fill="freeze" />
  </rect>
</svg>

<button onclick="go();">Go</button>

(W3C 2018,“ SVG动画级别2,编辑者的草稿”,https://svgwg.org/specs/animations/),“控制动画时间的属性”,“开始”属性,“不确定”值类型,{ {3}}