Search code examples
cssgsap

Convert keyframes to JS and/or GSAP


I've spent far too long trying to get a CSS animation to work on MS Edge to ever warrant it's use but thought I'd ask here as it would be a nice thing to solve before I lose any more hair.

I have an SVG animated with CSS which works a treat in Chrome and Firefox which I animate it like this:

svg {
    stroke-dasharray: 187;
    stroke-dashoffset: 0;
    transform-origin: center;
    animation: innerRotator 1.4s ease-in-out infinite;
}

innerRotator looks like this:

@keyframes innerRotator {
    0% {
        stroke-dashoffset: 187;
    }
    50% {
        stroke-dashoffset: 46.75;
        transform: rotate(135deg);
    }
    100% {
        stroke-dashoffset: 187;
        transform: rotate(450deg);
    }
}

I've tried and tried to figure this out so that it'll work on Edge and thought that GSAP might do the trick but my GSAP-foo is not strong and this is as far as I've managed to get... with poor results I might add.

var $spinner = $(".svg_spinner");
var tl = new TimelineLite();
tl.to($spinner, 0.7, {
    strokeDashoffset:46.75
}).to($spinner, 0.7, {
    strokeDashoffset:187
}).to($spinner, 0.7, {
    strokeDashoffset:46.75
});

Needless to say, it doesn't work.

Any help would be greatly appreciated.

Thank you for the comments :-)

A JSFiddle with my attempts so far is here: https://jsfiddle.net/annoyingmouse/64hv2328/ The innerRotator is the main issue as the outer one works a treat. I've replaced it with smil in the HTML which sort of works but isn't quite as smooth.


Solution

  • You had 2 issues:
    1. You forgot to specify units for stroke-dasharray and stroke-dashoffset which are required in Edge.
    2. IE and Edge do not support CSS transforms on SVG elements.

    Please look at the possible solution in the snippet below:

    .icon {
      display: block;
      animation: rotator .7s linear infinite;
      width: 65px !important;
      height: 65px !important;
      overflow: visible;
    }
    
    .icon circle {
      stroke-dasharray: 187px;
      stroke-dashoffset: 0;
      transform-origin: center;
      animation: innerRotator 2.8s ease-in-out infinite;
    }
    
    @keyframes rotator {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }
    
    @keyframes innerRotator {
      0% {
        stroke-dashoffset: 187px;
      }
      50% {
        stroke-dashoffset: 46.75px;
      }
      100% {
        stroke-dashoffset: 187px;
      }
    }
    <svg class="iconsvg icon">
        <circle class="svg_spinner" fill="none" stroke-width="6" stroke="black" stroke-linecap="round" cx="32.5" cy="32.5" r="30"/>
    </svg>