Wwjdtd
Wwjdtd

Reputation: 11

Steps in Web Animations API

I was wondering if there is a way of making a web animation go step by step using the web animation API without having to manually declare offsets for the start and end of each frame. Obviously you can do this in CSS animations.

This is for animating sprite sheets.

Upvotes: 1

Views: 740

Answers (1)

brianskold
brianskold

Reputation: 972

Yes, you can use the same approach as in CSS animations. That is, you can specify a timing function using the easing property. Unlike CSS animations you can either apply this to the whole animation or between individual keyframes.

To apply it to the whole animation you can use:

elem.animate(/* ...keyframes ...*/, { duration: 1000, easing: 'steps(5)' });

Alternatively, to apply to individual keyframes you can use one of the following approaches:

// Keyframe array syntax
div.animate(
  [
    { opacity: 0, easing: 'steps(2)' },
    { opacity: 0.5, offset: 0.8, easing: 'steps(3)' },
    { opacity: 1 },
  ],
  {
    duration: 1000,
  }
);

// Object syntax
div.animate(
  {
    opacity: [0, 0.5, 1],
    offset: [0, 0.8, 1],
    easing: ['steps(2)', 'steps(3)'],
  },
  {
    duration: 1000,
  }
);

Note that CSS animations can only do easing between keyframes. It cannot do easing across the whole animation.

Also, note that when applied to keyframes, the easing is used from the keyframe it is added to until the next keyframe. As a result, it is not necessary to add easing to the last keyframe.

If you are animating sprite sheets, you might find the jump-none keyword useful. It is supported by Firefox and Chrome. For example, use steps(5, jump-none) to see all five frames.

Upvotes: 1

Related Questions