What is the cubic Bézier easing in Anime.js?

What is easing?

An easing is the rate of change in animation progress. In Anime.js, we can use a user-defined cubic Bézier curve to create an easing.

A cubic Bézier curve is a smooth curve defined by four points: P0P_0, P1P_1, P2P_2, and P3P_3. In the context of animation, P0P_0 and P3P_3, are fixed to (0,0)(0,0) and (1,1)(1,1), respectively. This represents the start and end of the animation.

P1P_1 and P2P_2 usually don't lie on the curve, but are used to guide the curve. The following equation is used to generate a cubic Bézier curve:

Here, tt is the current time of the animation. 00 represents the start, while 11 represents the end of the animation. The illustration below describes some cubic Bézier curves:

Cubic Bézier curves with various P1 and P2 values

Syntax

The following is the syntax to create a cubic Bézier easing:

anime({
   ...
   easing: 'cubicBezier(x1, y1, x2, y2)',
});

The cubicBezier value takes four parameters. The x1 and y1 parameters are coordinates of P1P_1, while x2 and y2 are coordinates of P2P_2. As mentioned previously, P0P_0 and P3P_3 are assumed to be (0,0)(0,0) and (1,1)(1,1).

Example

For the following example, we create a simple sliding box animation and set its easing to follow the cubic Bézier curve given below:

The cubic Bézier curve that we will use as an easing
Use the cubicBezier easing with Anime.js

Explanation

In the HTML section, we create a box using a div element and style it using the box class.

In the JavaScript section, we create the animation using the anime() function.

  • Line 2: We target the div element using its box class.
  • Lines 3–5: We set parameters to control the box's horizontal movement and timing.
  • Line 6: We set the easing parameter to 'cubicBezier'. We pass the coordinates of P1P_1 (0.2,1.0)(0.2, 1.0) and P2P_2 (0.8,0)(0.8, 0) as described in the previous illustration.

As we can see, the progression of the animation mimics the cubic Bézier curve. The box slows down to a stop at the midpoint and then speeds up to the finish point.

In the same manner, any cubic Bézier curve can be used as an easing by providing coordinates for P1P_1 and P2P_2.

Copyright ©2024 Educative, Inc. All rights reserved