Skip to content本文へ移動

Frames, timing & animation

Make motion a function of the frame.

A composition’s duration in seconds is durationInFrames / fps. At 30 fps, 150 frames make five seconds, with frame indices from 0 through 149. Use useCurrentFrame() inside a composition to calculate animated values.

Interpolate between values

The title example uses Math.min(frame / 30, 1) for opacity. For easing and more control, import interpolate and Easings from @celesta.studio/react, then replace the calculation with:

const opacity = interpolate(frame, [0, 30], [0, 1], {
  easing: Easings.easeOut,
  extrapolateLeft: 'clamp',
  extrapolateRight: 'clamp',
});

Pass the result to <Text opacity={opacity} … />. Input ranges must be strictly increasing and have the same number of entries as the output range. The input and every range entry must be finite numbers: a NaN, such as one from a misspelled field, throws an error instead of returning NaN. Extrapolation defaults to extend; use clamp to hold the first and last values.

Easings covers the familiar easings.net curves: linear, and the easeIn/easeOut/easeInOut variants of Sine, Quad, Cubic, Quart, Quint, Expo, Circ, Back, Elastic, and Bounce (for example Easings.easeOutBack). For a whip pan there is also Easings.whip: it barely moves at both ends and covers 98% of the move in its middle third, at up to seven times the average speed ('whip' in JSON keyframes).

When a named curve is not quite right, build one from numbers:

const pop = Easings.back(2.2).easeOut;              // a stronger overshoot than easeOutBack
const material = Easings.cubicBezier(0.4, 0, 0.2, 1); // the same four numbers as CSS cubic-bezier()
const tick = Easings.steps(6);                      // six equal steps
const wobble = Easings.elastic({ amplitude: 1.5, period: 0.4 }).easeOut;

Easings.back(overshoot) and Easings.elastic({ amplitude, period }) return { easeIn, easeOut, easeInOut }. Easings.cubicBezier needs x1 and x2 between 0 and 1; y1 and y2 may go outside, which makes the curve overshoot. Pass the result anywhere an easing goes: interpolate's easing, progress, or a component's easing prop. Keyframes in a JSON project take the named curves only.

Move through keyframes

interpolate uses one easing for every segment. When each leg of a move needs its own curve, or several numbers move together, use keyframes from @celesta.studio/react. Each key has a frame, a value (a number, or an object of numbers), and optionally the easing of the move that arrives at it:

const cam = keyframes(frame, [
  { frame: 0,   value: { x: 960, y: 540, zoom: 1 } },
  { frame: 100, value: { x: 880, y: 520, zoom: 1.12 }, easing: Easings.easeInOutCubic },
  { frame: 120, value: { x: 880, y: 520, zoom: 1.12 } },  // the same value: a hold
  { frame: 120, value: { x: 300, y: 400, zoom: 1 } },     // the same frame: a cut
]);

<Camera {...cam}>
  <World />
</Camera>

Before the first key the value is the first key's, and after the last key the last key's. Two keys on one frame cut: that frame already shows the second key's value. easing is a function, or the name of a curve as JSON keyframes spell it ('ease-out-back'). Keys must be in order of frame, and every value must have the same fields. For the volume of an <Audio>, which takes keyframes itself, use frameKeyframes instead; see Media.

Drift during a hold

A held camera that stands perfectly still can look frozen. Give the key a drift and the value keeps creeping while it holds after that key, at a rate per second, so pass the composition's fps:

const { fps } = useVideoConfig();
const cam = keyframes(frame, [
  { frame: 0,   value: { x: 960, y: 540, zoom: 1 } },
  { frame: 100, value: { x: 880, y: 520, zoom: 1.12 }, easing: Easings.easeInOutCubic,
    drift: { x: -4, zoom: { log: 0.006 } } },
  { frame: 160, value: { x: 880, y: 520, zoom: 1.12 } },  // the drift runs to here
  { frame: 180, value: { x: 300, y: 400, zoom: 1 }, easing: Easings.whip },
], { fps });

For an object value, drift has a rate for each field that moves (x: -4 is 4 pixels to the left each second); a number value takes one rate. { log: r } multiplies instead of adding, by about 1 + r each second, so a zoom creeps at an even pace. A field drifts only while it holds: up to the next key when that key has the same value for it, or forever after the last key. The move after the hold starts from wherever the drift reached, so nothing jumps, and a cut starts from its own key. Every frame is still computed from the frame number alone.

Interpolate between colors

Import interpolateColor from @celesta.studio/react too. It takes the same input range and easing as interpolate, but maps the frame onto #RRGGBB or #RRGGBBAA colors and returns #RRGGBBAA. Use it wherever a color goes: a Rect fill, a text style’s fill, a gradient stop, or a shadow.

const sky = interpolateColor(frame, [0, 45, 90], ['#101820', '#EF7B45', '#7FC8F8']);
const title = interpolateColor(frame, [0, 20], ['#FFFFFF00', '#FFFFFF']);

<Rect width={1920} height={1080} fill={sky} />
<Text style={{ fontSize: 96, fill: { type: 'solid', color: title } }}>Morning</Text>

Unlike interpolate, extrapolation defaults to clamp, so the first and last colors hold outside the range; extend continues the end segments, and identity is not available. Colors blend in sRGB with premultiplied alpha, as gradients and CSS do: a color fading to #00000000 keeps its hue instead of darkening, and channels that extend or an overshooting easing push out of range are clamped. CSS color names, rgb(), and the short #RGB form are not accepted.

Add a little bounce

spring() simulates a damped spring: it starts at 0, settles at 1, and may overshoot on the way. It needs the frame rate, so read it from useVideoConfig():

function Badge() {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const scale = spring({ frame, fps, delay: 10, config: { damping: 12 } });
  return (
    <Rect x={960} y={540} anchorX={0.5} anchorY={0.5} scale={scale}
      width={320} height={120} cornerRadius={60} fill="#78618e" />
  );
}

Tune the feel with config: stiffness (default 100), damping (default 10), mass (default 1), and overshootClamping. Use from and to to map the result to another range. frame, delay, from, and to must be finite numbers, fps a finite number above 0, and durationInFrames, when set, a number other than NaN (Infinity is the same as leaving it out); anything else throws an error.

Place a scene on the timeline

Import Sequence to delay or limit a group of layers. This shows the Title component from the previous example starting at frame 30 for 90 frames:

<Sequence from={30} durationInFrames={90}>
  <Title />
</Sequence>

Within that sequence, useCurrentFrame() starts at 0 when the sequence begins. Child video and audio use the same local clock. Children contribute neither layers nor audio outside the sequence’s time window.

from defaults to 0 and must otherwise be a finite number; it may be negative. Leave durationInFrames out, or set it to Infinity, to run until the end of the enclosing sequence or composition; 0 is an empty window. A from that is NaN, infinite, or not a number, and a durationInFrames that is NaN, negative, or not a number, throw an error that names the prop, so a timing computed from a misspelled field fails instead of covering every later scene.

Repeat a scene

<Loop durationInFrames> plays its children over and over: every durationInFrames frames, their clock starts again at 0. Use it for a background animation or a short piece of music that repeats:

<Loop durationInFrames={60}>
  <Pulse />
</Loop>
<Loop durationInFrames={120} times={3}>
  <Audio src="./phrase.wav" />
</Loop>

Inside, useCurrentFrame(), <Video>, <Audio>, and nested sequences all restart with each cycle, and useVideoConfig().durationInFrames is one cycle’s length. from sets where the first cycle starts, like a Sequence’s. Without times, the loop repeats until the enclosing sequence or composition ends; a fractional times such as 2.5 cuts the last cycle short. Each cycle’s audio is a clip of its own, cut where the loop ends. Only the current cycle is mounted, so any frame you scrub to looks the same as in the export.

Redraw a past frame

Every frame is a function of the frame number, so <FreezeFrame frame> can draw any moment of the video again in place, for a rewind, a flashback, or a row of thumbnails. frame counts on the whole composition’s clock, even inside a Sequence:

<Group scale={0.25} x={80} y={80}>
  <FreezeFrame frame={1200}>
    <World />
  </FreezeFrame>
</Group>

Directly inside, useCurrentFrame() returns frame, rounded to a whole frame (a Sequence within it still counts from its own start), and sequences, video, lip sync, and blinking all show that moment. A fixed frame holds still; with frame read from useCurrentFrame() in your root component, frame={frame - 90} replays 90 frames behind (three seconds at 30 fps). Frozen children are silent. A CharacterView drawn inside leaves its ref to the live view, and a Dialogue inside drives only a view inside the same FreezeFrame. Project layers (ProjectTimeline, ProjectTrack) are evaluated for the current frame only and cannot be drawn inside. A video may hold a smaller copy of itself, but a FreezeFrame whose frame plays that same FreezeFrame again would draw itself forever, so it throws an error naming the frames involved, as does nesting FreezeFrames more than 16 deep.

Blur fast motion

Something that moves far between two frames jumps from one place to the next. <MotionBlur> draws its children at several moments while a shutter is open around the frame and shows their average, so the movement smears the way a camera sees it:

<MotionBlur shutterAngle={180} samples={8}>
  <DashingCard />
</MotionBlur>

shutterAngle is how long the shutter stays open, in degrees of a frame: 180 (the default) is half a frame, centered on the frame, and 360 a whole frame. samples (8 by default) is how many moments are averaged; each one draws the children again, so a blur costs about that many times the children. When very fast motion shows steps instead of a smooth smear, raise samples.

Inside, useCurrentFrame() returns each moment’s frame, such as 12.25, so components that animate from it move between the moments. Code that indexes an array by the frame needs Math.floor there. Props you compute outside, such as a Camera’s x, are the same in every moment; pass a function to compute them per moment instead:

<MotionBlur>
  {(frame) => (
    <Camera x={interpolate(frame, [0, 30], [0, 3000], { extrapolateRight: 'clamp' })}>
      <World />
    </Camera>
  )}
</MotionBlur>

The result of a frame does not depend on which frames were drawn before it, and the editor preview draws the same blur as the export. Moments stay within the enclosing Sequence, so the first and last frames of a shot do not fade. <Video>, animated images, lip sync, and blinking keep the frame’s picture in every moment (footage already carries the blur of its own camera), and audio and subtitles inside play once. Every moment is a copy, like a FreezeFrame’s: a CharacterView inside leaves its ref alone, so put its Dialogue inside too. Project layers cannot be drawn inside. The blurred layer takes a group’s props (x, opacity, blendMode, blur, …), which apply to the average.

Leave a trail

<Trail> draws earlier copies of its children beneath them, each lagInFrames frames older and fainter than the one above:

<Trail copies={4} lagInFrames={1.5} trailOpacity={0.5}>
  <Ball />
</Trail>

The newest copy is drawn at trailOpacity and each older one fades by the same step. A copy fades as a Group with that opacity does, so overlapping layers within one copy show through each other. Copies from before the enclosing Sequence began are not drawn. Inside a copy, useCurrentFrame() and the rules for video, audio, and characters are those of MotionBlur; the children on top are the live ones.

Ready-made entrances and exits

<Transition> fades, slides, or scales its children at the start (direction="in", the default) or end (direction="out") of the enclosing sequence:

<Sequence from={30} durationInFrames={120}>
  <Transition type="slide" slideFrom="bottom" durationInFrames={15}
    easing={Easings.easeOutCubic}>
    <Transition type="fade" direction="out" durationInFrames={20}>
      <Caption />
    </Transition>
  </Transition>
</Sequence>

Slides travel distance pixels (64 by default); scales start from scaleFrom (0.8 by default). Pass several types to combine them, such as type={['fade', 'slide']}.

Celesta holds every frame to this while it renders, in the preview, in exports, and when an agent inspects the composition:

  • Math.random() starts again on every frame from a seed made from that frame’s time. A frame always gets the same numbers, whatever order frames render in, and the next frame gets different ones, so a shape placed with Math.random() jumps every frame.
  • Date.now(), performance.now(), and new Date() read the frame’s time in milliseconds, as if the video started at 1970-01-01 00:00 UTC: at 1.5 seconds, Date.now() is 1500. A new Date() with a value, Date.parse(), and Date.UTC() work as usual.
  • Inside a <FreezeFrame>, a <MotionBlur> sample, or a <Trail> copy, both follow that moment instead, so a frozen scene keeps its values.
  • When the composition (or a package or plugin it uses) calls one of them while rendering, Celesta warns once: nondeterministic_render: the entry calls Math.random() …. The app lists it with the preview’s warnings in Problems, and celesta-exporter prints it (warnings in --json).

Module scope and prepare() run before any frame, with the real clock and Math.random(). Read today’s date or time a request there, and keep the result in a module variable so every frame reads the same value.

Hold a scene at one frame

<FreezeFrame frame={60}> draws its children at root composition frame 60, even when wrapped in a Sequence. Child hooks, video, lip sync, and blinking follow that time; nested sequences still apply their own offsets. Audio inside FreezeFrame is muted.

<FreezeFrame frame={60}>
  <AnimatedTitle />
</FreezeFrame>

Try it without installing.

The playground runs Celesta in your browser, export included.

Open the playground