DEV Community

Cover image for Building Rocket: Starting Animating!
Knitely
Knitely

Posted on

Building Rocket: Starting Animating!

animate() Function

Think of animate() as the friendly function or API that does the heavy lifting to bring your elements to life. To get your hands on it, first install Rocket:

npm i rocket-animation
Enter fullscreen mode Exit fullscreen mode

Or pull it straight in via CDN (zero install required!):

import { animate } from "https://cdn.jsdelivr.net/npm/rocket-animation@1.0.13/+esm";
Enter fullscreen mode Exit fullscreen mode

Here’s the signature:

animate(target: TargetElement, param: JSAnimationParameter): JSAnimation
Enter fullscreen mode Exit fullscreen mode

Parameter List

  • target: Can be an HTMLElement or a string (like a CSS selector).
  • param: An object of type JSAnimationParameter.

JSAnimationParameter

This object holds all the key-value settings for your animation. Check out the table below to see what each option does:

Key Description Default Value Type Unit
x Horizontal translation offset of the animated element along the X-axis. 0 number/string px, rem, em, etc.
y Vertical translation offset of the animated element along the Y-axis. 0 number/string px, rem, em, etc.
rotate Rotational angle applied to the element in 2D space. 0 number deg
scale Uniform scaling factor applied equally to both horizontal and vertical axes. 1 number none
scaleX Horizontal scaling factor along the X-axis. 1 number none
scaleY Vertical scaling factor along the Y-axis. 1 number none
duration Length of a single animation cycle before completion or looping. 500 number ms (milliseconds)
delay Initial wait time before the animation begins playing after trigger. 0 number ms (milliseconds)
loop Number of times the animation repeats (0 for none, true or Infinity for continuous looping). 0 number/boolean/Infinity none
loopDelay Pause duration inserted between repeated loop iterations. 0 number ms (milliseconds)
alternate Reverses direction on every other cycle (ping-pong / yoyo behavior) when looping. false boolean none
onFinish Callback invoked when the animation finishes all cycles and completes. noop AnimationCallback ((arg?: Flowable) => void) none
onLoop Callback invoked at the end of each repeated loop iteration. noop AnimationCallback ((arg?: Flowable) => void) none
onPause Callback invoked whenever playback of the animation is paused. noop AnimationCallback ((arg?: Flowable) => void) none
onStart Callback invoked once when the animation initially starts running (after any delay). noop AnimationCallback ((arg?: Flowable) => void) none

There are more JSAnimationParameter keys beyond the ones listed above—we’ll cover those later in the series, so don’t worry about memorizing everything at once!


Making Your First Animation

This snippet animates an element from its current spot to whatever destination you specify:

import { animate } from "https://cdn.jsdelivr.net/npm/rocket-animation@1.0.13/+esm";

let t = animate(".ball", {
  x: 535, // Moves the ball 535px from its original position along the X-axis
  duration: 1500,
});
Enter fullscreen mode Exit fullscreen mode

Want to work backward instead? Use animate.from() to animate a target from a given state back to its initial position:

import { animate } from "https://cdn.jsdelivr.net/npm/rocket-animation@1.0.13/+esm";

let t = animate.from(".ball", {
  x: 535, // Moves the ball from 535px back to its starting point (0) along the X-axis
  duration: 1500,
});
Enter fullscreen mode Exit fullscreen mode

You can also take the wheel with pause(), reverse(), play(), and resume():

pause.onclick = () => t.pause();

reverse.onclick = () => t.reverse();

play.onclick = () => t.play();

resume.onclick = () => t.resume();
Enter fullscreen mode Exit fullscreen mode

Go ahead and play around with the examples above! If you spot any bugs or quirks in my implementation, drop a comment below or open an issue on GitHub.


JSAnimation Class (Under the Hood)

To pull off smooth animations in Rocket, we use JSAnimation—a class that extends Flowable. This is where the real magic happens: watching a target element slide across an axis, shrink, grow, spin, and more over a set duration.

JSAnimation relies on a render() method to keep things smooth, and it expects:

  • The target elements we want to animate.
  • The animation properties we want to apply, such as translation (x, y), rotate, scale, and so on.
  • A few optional parameters, which we’ll explore later in this post.

Animation Properties

Animation properties are simply the visual traits you want to change on a target—like sliding an element by a few pixels, spinning it a few degrees, or tweaking its width or height. Rocket groups these into two camps:

  • Transform properties: Properties driven by CSS or JS transform, including:
    • x, y, or translate(x, y)
    • scale, scaleX, or scaleY
    • rotate By default, transform properties start at 0—except scale (and its variants), which start at 1.
  • Non-transform properties: Properties you can update directly on CSS or JS styles, like width, height, or opacity. Unlike transform properties, they don’t have a neat default of 0 or 1, so we grab their initial value straight from the element to keep the animation smooth and consistent.

Rocket lets you animate multiple properties at the exact same time—for example, sliding an element 200px along the X-axis while spinning it 360deg. To make that happen, we loop through the requested properties and collect a few key details for each one:

  • from: The property’s starting value on the element.
  • to: The target value you want the element to reach.
  • unit: The measurement unit you provided (like px or rem).
  • currentState: The live value of the property as the animation runs, updated along the way so you always know where things stand.

Now let’s peek at how render() actually moves things forward!


How Does render() Make This Animation?

To keep animations smooth, render() accepts three arguments: time, isSeek, and forceAnimate. For now, let’s focus on time—a clamped value between 0 and the animation’s duration, passed down from a parent Container or Flowable.

First, we turn time into a progress ratio between 0 and 1 by dividing time / duration. Let’s call that ratio t. Once we have t, we plug it into linear interpolation (lerp) to figure out where the element should be at that exact moment:

  lerp = from + (to - from) * t 
Enter fullscreen mode Exit fullscreen mode

where:

  • from is the starting value of the property on the target element.
  • to is the ending (target) value of the property.

Finally, we take that interpolated value and apply it to the element. Because Rocket can animate multiple elements and multiple properties at once, each pass follows this loop:

  1. Loop through each target element, then loop through its properties to grab from, to, and currentState.
  2. Calculate the lerp value and update currentState.
  3. Save the property data onto the element under rocketCache.
  4. Apply the updated currentState to the target element.

That’s the short version of how rendering works under the hood! If you want to dig deeper, check out the source code on the GitHub repo—and if you have any questions, ask away in the comments.

That wraps up this post! Next time, we’ll dive into Timeline. In the meantime, don’t forget to star the Repo and follow me on Telegram, X (Twitter), or GitHub if you haven’t already!

Top comments (0)