You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SVG.js动画时间线完成后执行函数并反转动画失效问题求助

问题描述

使用SVG.js创建绑定到SVG元素的时间线动画,期望动画执行完成后运行指定函数,再将动画反转回初始状态。使用.after()绑定回调函数后,函数可正常执行,但runner.reverse()无法生效,寻求其他实现方式。

代码示例

var timeline = new SVG.Timeline().persist(true);                
var draw = SVG().addTo('#drawing').size(800, 800);
var rect = draw.rect(50, 50).attr({fill: '#f06', id :'rect'});
var runner = rect.animate();
runner.animate(9900,100,'absolute').rotate(40)
      .animate(9900,100,'absolute').translate(200,200)
      .animate(9900,100,'absolute').scale(0.6)
      .animate(9900,100,'absolute').attr({fill:'#ccccff'})
      .animate(9900,100,'absolute').attr({stroke:'#6666ff'})
      .after(function() {doOnFinish(rect)});

function doOnFinish(obj){
  console.log('RUN ONCE FINISHED ***********************');
  console.log('obj : ' + obj);
  for(var i in obj){
      console.log(i);
  }
  runner.reverse();
}
解决方案

问题出在动画完成后,原runner实例的动画状态已结束,无法直接通过reverse()触发反向播放。可以通过以下两种方式解决:

方式一:绑定自定义时间线并操作时间线反转

你已经创建了timeline但未绑定到动画上,只需将时间线关联到动画实例,之后直接反转时间线即可:

var timeline = new SVG.Timeline().persist(true);                
var draw = SVG().addTo('#drawing').size(800, 800);
var rect = draw.rect(50, 50).attr({fill: '#f06', id :'rect'});
// 将自定义时间线绑定到动画
var runner = rect.animate({ timeline: timeline });
runner.animate(9900,100,'absolute').rotate(40)
      .animate(9900,100,'absolute').translate(200,200)
      .animate(9900,100,'absolute').scale(0.6)
      .animate(9900,100,'absolute').attr({fill:'#ccccff'})
      .animate(9900,100,'absolute').attr({stroke:'#6666ff'})
      .after(function() {
        console.log('RUN ONCE FINISHED ***********************');
        // 反转时间线
        timeline.reverse();
      });

原理:自定义时间线persist(true)会保留动画状态,动画完成后直接反转时间线即可驱动元素回到初始状态。

方式二:在回调中重新创建反向动画序列

如果不想依赖自定义时间线,可以在after回调中手动定义反向的动画步骤:

var draw = SVG().addTo('#drawing').size(800, 800);
var rect = draw.rect(50, 50).attr({fill: '#f06', id :'rect'});
var runner = rect.animate();
runner.animate(9900,100,'absolute').rotate(40)
      .animate(9900,100,'absolute').translate(200,200)
      .animate(9900,100,'absolute').scale(0.6)
      .animate(9900,100,'absolute').attr({fill:'#ccccff'})
      .animate(9900,100,'absolute').attr({stroke:'#6666ff'})
      .after(function() {
        console.log('RUN ONCE FINISHED ***********************');
        // 反向执行动画步骤
        rect.animate(9900,100,'absolute').attr({stroke:'transparent'})
            .animate(9900,100,'absolute').attr({fill:'#f06'})
            .animate(9900,100,'absolute').scale(1)
            .animate(9900,100,'absolute').translate(0,0)
            .animate(9900,100,'absolute').rotate(0);
      });

原理:动画完成后,按照原动画的逆序重新定义动画步骤,让元素逐步回到初始状态。


内容的提问来源于stack exchange,提问作者starrezzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:15:02