roest
roest

Reputation: 376

Animate an SVG sprite with CSS

I’ve got some svg sprites and want to animate them on a website. What is the recommended way to use these files?

First, this is my Hunter (raw covert) - I got it as eps and converted to svg via indesign.

My entry is to animate it via css by changing the current picture in a keyframes animation.

Ideas:

  1. I found this wonderful blogpost where the current image is selected via anchor
  2. Use background position

So I’ve identified the different images in my file, gave them an ID and hidden the others. You can interconnect with #a #b #c ....

Hunter Image #a

-> Problem: Position on the sprite is still different. I had to change the background position as well.

https://jsfiddle.net/roest/035r0ozq/

0% {
    background-image: url(http://elefantenjagdverein.de/server/elephants/hunter/hunter.hidden.svg#a);
  }
  20% {
    background-image: url(http://elefantenjagdverein.de/server/elephants/hunter/hunter.hidden.svg#b);
  }

Entry 2 - use background-position like a normal sprite ... But something still seems broken.

If you use getspritexy.com with a normal sprite you see within "Generated sprite image" the selection. with my svg you see multiple images ... Same result in my testFiddle:

https://jsfiddle.net/roest/4bbnnm9t/

0% {
        background: url('http://elefantenjagdverein.de/server/elephants/hunter/hunter.svg') no-repeat -83px -15px;
        width: $width;
        height: $height;
      }
      20% {
        background: url('http://elefantenjagdverein.de/server/elephants/hunter/hunter.svg') no-repeat -131px -15px;
        width: $width;
        height: $height;
      }

Which of my ideas is the best and how can i get my hunter to animate correctly?

Upvotes: 1

Views: 2024

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101956

To have your frames step from one position to anothe without sliding, you can use step-end for the timing function.

animation: hunter-animation 2.5s step-end both infinite;

See: https://jsfiddle.net/4bbnnm9t/3/

Now that it steps, you just have to adjust the positions so they are correct.

Upvotes: 2

Related Questions