Web Animation API allows us to create key-frame animations using JavaScript. In this tutorial I will introduce you to Web Animation API with some demos.
What is Key-Frame Animations
A key-frame animation is an animation which is of fixed time length and key frames in the animation define the position of objects of the animation at various time intervals.
A Quick CSS3 Key-Frame Animation Revision
CSS3 Key-frame animation let us animate HTML elements without any scripting.
Here is an demo
In the above demo we are moving a box horizontally.
You need to create an key-frame animation using @keyframes
rule. @keyframes
lets you define the position and behavior of an object at different point of time in the animation.
Once you have created an animation you need to attach the animation to an HTML element using animation
CSS property. animation
property lets you define the total length of the animation.
One same @keyframes
rule or animation can be applied to many different HTML elements.
A Look at Web Animation API
Web Animation API lets us create key-frame animations using JavaScript. We don’t need to learn CSS3 animations to work with Web Animation API. It aims to make things easier by providing better performance, more control over timing and playback and a flexible and unified javaScript programming interface which is what is lacked by CSS3 Animations.
Web Animation has is still under development and not yet completely supported by all browsers. Therefore you have to use Web Animation JS Polyfill.
Here is the same animation we created above but using Web Animation API
Most of the JavaScript code in the demo is self understanding. One of the things that may be confusing is the offset property.
Each keyframe of the animation is specified by using a offset
property which is in the range [0, 1]. The first keyframe starts with 0 i.e., 0% and the last keyframe ends with 1 i.e., 100%.
In the above example we animated only margin property of the box. If you want to animate multiple properties then you need to call animate
function multiple times with the desired properties.
Here is an demo for animating height and margin
Final Thoughts
As the specification gets closer to stable I will be updating this article equally. The polyfill supports many other interfaces of the specification but in this tutorial I just gave an overview of it.