Search code examples
csssvgcss-animationssvg-animate

svg inline css animation keyframes timing


I want to make an animated svg logo using css animation with keyframes. The animation works well, but I can not find a way to properly time the keyframes.

I want to achieve the below timeline:

  • step 1: 4 seconds pause (the original image should be shown),
  • step 2: 2 seconds animation (one full circle of horizontal rotation),
  • step 3: 4 seconds pause (the original image should be shown),
  • step 4: 2 seconds animation (one full circle of vertical rotation),
  • step 5: repeat step 1-4 infinitely.

I have the below svg code:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 20">
<defs><style>
.txtme {
transform-origin: center;
animation: anime 12s linear 3s infinite;
}
@keyframes anime {
33% { transform: rotate3d(0, 1, 0, 360deg); }
66% { transform: rotate3d(1, 0, 0, 360deg); } 
}
</style></defs>
<text class="txtme" fill="#000" x="25%" y="50%" style="font-family:sans-serif;">MyLogo</text>
</svg>

Could you please help me how could I achieve the above timeline using css keyframes.


Solution

  • To build 12s animation with provided requirements I might recommend to remove the animation-delay and manipulate with animation inside keyframes.

    First step is to transform seconds to keyframe percentage:

    • 4s of animation is 33%
    • 2s of animation is 17%

    Second step is to calculate keyframe percentage based on requirements:

    • 1st delay should be from 0 to 33%; (0-4s)
    • 1st rotation should be from 33% to 50%; (4s-6s)
    • 2d delay should be from 50% to 83%; (6s-10s)
    • 2d rotation from 83% to 100%; (10s-12s)

    So the solution is:

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 20">
    <defs><style>
    .txtme {
        transform-origin: center;
        animation: anime 8s linear 4s infinite;
    }
    @keyframes anime {
        33% { transform: rotate3d(0, 0, 0, 0deg); }
        50% { transform: rotate3d(0, 1, 0, 360deg); }
        83% { transform: rotate3d(1, 0, 0, 360deg); }
        100% { transform: rotate3d(1, 0, 0, 0deg); }
    }
    </style></defs>
    <text class="txtme" fill="#000" x="25%" y="50%" style="font-family:sans-serif;">MyLogo</text>
    </svg>