0

I'm trying to loop a sequence of animation on a simple block. However I cannot make my block go back to its original position.

var draw = SVG('drawing').size(300, 300);
var rect = draw.rect(50, 50).attr({ fill: '#a3c' });

function animLoop(obj){
  obj.rotate(0).move(10,10)
    .animate(500, ">").rotate(50)
    .animate(200, "<").rotate(45)
    .animate(200, "<").move(10,15)
    .after(function(s){
      animLoop(this);
    });
}

animLoop(rect);
#drawing {
    border-style: solid;
    border-width: 2px;
    border-color: purple;
    width: 300px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.5.1/svg.min.js"></script>
<div id="drawing"></div>

I'm looking for how to loop a sequence of animation with SVG.js but no luck. I tried to create my own so I might have done something wrong.

Pue-Tsuâ
  • 116
  • 1
  • 6

2 Answers2

2

Thanks for your question @Hankofficer. As @Fuzzyma said, you need to untransform the transformations added during the animation. Unfortunately, this is undocumented but we're working on an update.

We garbage collect animations to avoid unintentional memory leaks, similar to how jQuery handle animations. So the .loop() method only works on the last animation. In the future we might offer a .loopAll() method but this still in the discussion phase.

Here is a working example:

'use strict'

var draw = SVG('drawing').size(300, 300)
var rect = draw.rect(50, 50).attr({ fill: '#a3c' })

animLoop(rect)

function animLoop(obj) {
  obj.untransform()
    .animate(500, ">").rotate(50)
    .animate(200, "<").rotate(45).dmove(0,5)
    .animate(500, ">").rotate(0).move(10,10)
    .after(function() {
      animLoop(this)
    })
}
#drawing {
    border-style: solid;
    border-width: 2px;
    border-color: purple;
    width: 300px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.5.1/svg.min.js"></script>
<div id="drawing"></div>
dotnetCarpenter
  • 10,019
  • 6
  • 32
  • 54
  • Thanks so much! I'm new to SVG so there is a lot to explore, especially animation. It'd be nice to see more examples. :) – Pue-Tsuâ Apr 05 '17 at 00:33
  • Definitely. We have more examples on our documentation roadmap; https://github.com/svgdotjs/svg.js/projects/2#card-1789655 @RmiTtro just made a proof of concept for a `.loopAll()` method; https://github.com/svgdotjs/svg.js/pull/649 – dotnetCarpenter Apr 06 '17 at 10:59
1

Having a loop of sequences in svg.js is not implemented for good reasons. However your way is completely valid and the way to go when you want to loop multiple sequences.

Please note that absolute transformations like you use with rotate(0) are rather inaccurate. That is due to the nature of transformations in general and is no bug or something.

So if you wanna reset the transformation correctly use untransform() instead of rotate(0) and it should work as expected.

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60