The missing snap.svg function

Snap.svg is one of my favourite tools to use right now to create easy, interesting, scalable animations. There is one function that would have been great if included in the initial specification.

Now, I understand that this may be a user case issue, and the majority of people do not need to do this. However, to create complex animations, an animate this element along this path function is a must have. It's purpose will allow you to define a path to copy, and then pass an element to apply the animation.

So here is the code:

animateAlongPath = function (path, el, start, duration, easing, callback) {
  var len = Snap.path.getTotalLength(path), 
      elBB =  el.getBBox(),
      elCenter = {
        x: elBB.x + (elBB.width / 2),
        y: elBB.y + (elBB.height / 2),
      };

  Snap.animate(start, len, function (value) {
    var movePoint = Snap.path.getPointAtLength(path, value);
    el.transform('t'+ (movePoint.x - elCenter.x) + ',' + (movePoint.y - elCenter.y));
  }, duration, easing, function () {
    if (callback) callback(path);
  });
};

I have added a couple of little extras to make it easier to use. You can send in your easing function if you wish, or just use the built in 'mina' easing algorithms from snap.svg. Also, it provides a simple callback functionality which is commonplace in animation libraries.

Here the code is in action:

See the Pen GgzNdy by Michael Tempest (@mike-tempest) on CodePen.

Comments