What are animation keyframes in anime.js?
Overview
Anime.js is a JavaScript library that allows us to easily create animations. The keyframes parameter lets us create complicated animations by breaking them down into a list of steps. Each step executes one after the other. We refer to a single step as one keyframe.
Syntax
The following code is the syntax for creating animation keyframes. We use the keyframes property and provide it with a list of objects.
anime({
keyframes: [
{property: value, property parameter: value},
{property: value, property parameter: value},
{property: value, property parameter: value},
],
});
Each object in the list is a keyframe. We can use any property in the list of keyframes, and some property parameters can accompany each property.
Each keyframe can be given the duration parameter, which determines the time taken by the keyframe. If each keyframe does not have a duration parameter, the total duration is equally divided among all keyframes.
Example
In the following example, we use animation keyframes on a simple sliding box.
Explanation
In the HTML section, we create a box using the <div> tag and style it using the box class.
In the JavaScript section, we animate the box using the anime() function.
Line 2: We target the box using its class.
Lines 3–9: We provide a list of frames to the
keyframesparameter.Line 4: We define the first frame. In this frame, the box moves horizontally right to 150px over a duration of 300 milliseconds.
Lines 5–7: We define the second, third, and fourth frames similarly. The
translateXproperty results in a horizontal movement while thetranslateYproperty results in a vertical movement.Line 8: We define the fifth and last frame. We give this frame its own
easingof'easeOutBounce', which gives it a bouncing effect.Line 10: We add a delay to the start of the animation. The delay parameter does not apply to each frame; instead, it is only applied at the very beginning of the animation.
Line 11: We set the
easingparameter to'linear'. This ensures the box moves at a constant speed. This easing will apply to all but the fifth frame as we have already defined theeasingparameter for the fifth frame.
As we can see, the box executes each frame one after the other. Each frame lasts a different amount of time since we've specified the duration parameter for each.
Free Resources