How to add direction to animation in anime.js

Anime.js is a JavaScript library used to create animations. It provides the anime() function that takes key-value pairsPairs of two related elements "key" and "value" where the key defines the value as parameters such as targetsThe elements we want to animate and propertiesThe visual features we want to animate, like color, shape, and size.

Note: To get familiar with targets and properties in anime.js, click here for a basic overview.

We might require some animations to play normally and some in reverse. Anime.js provides us with the direction parameter to let us choose the direction of our animation.

Syntax

We use the direction parameter in the following way:

anime({
  ...
  direction: value,
  ...
});

The direction parameter can take one of three values:

  • normal
  • reverse
  • alternate

Normal

The animation will progress from 0% completion to 100% completion. In other terms, the animation will move from start to finish.

The 'normal' value is the default for the direction parameter. If the direction is not specified, the direction is set to 'normal'.

Setting the direction to 'normal'

Code explanation

We create a simple sliding box animation for this example:

  • Lines 1–5: We create animation and target the box. We set the animation to translate the box right to 450 px. We also set the duration and delay to 1000 milliseconds so the box doesn't pass by too quickly.
  • Line 7: We set the direction parameter to 'normal'. As a result, the animation proceeds from 0% (its current position) to 100% (its final position).
  • Line 8: We set an easing of 'linear'. This parameter ensures the box moves at a constant rate.

We can achieve the same motion if we omit the direction parameter.

Reverse

The animation will progress from 100% completion to 0% completion. In other terms, the animation will move from finish to start.

Setting the direction to 'reverse'

In the above example, we replicate the same animation but change the direction to 'reverse'. Now the box will start from 450px and move horizontally to the left side of the widget, opposite to the previous example.

Alternate

We may want to play normal and reverse animations back to back. Instead of chaining two separate animations, we can use the 'alternate' value for the direction parameter. This causes the animation first to play normally and then in reverse.

Setting the direction to 'alternate'

We have used the same animation to set the direction parameter to 'alternate'. As a result, the box moves right to its finish point and then back to its start point.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved