Pixi’VN

Animation (`AnimatedSprite`)

How to show, add, control and save frame-by-frame animations from a spritesheet on the canvas using the `AnimatedSprite` component (`showAnimatedSprite` / `addAnimatedSprite`, frame selection, per-frame durations, play/pause).

This component was introduced in version 1.9.9.

The AnimatedSprite component extends PixiJS.AnimatedSprite, so you can use all of its methods and properties. It is used to display a frame-by-frame animation, usually taken from a spritesheet (a JSON file + an image, as exported by TexturePacker, Aseprite, AssetPack, ...).

Unlike a plain PixiJS AnimatedSprite, the frames are described by an AnimatedSpriteSource: an object that contains only asset aliases and frame names. This is what Pixi’VN saves, so when the player loads a save or goes back, the animation is rebuilt with the same frames, the same current frame and the same playing state.

import { AnimatedSprite, canvas } from "@drincs/pixi-vn";

const explosion = new AnimatedSprite(
    {
        anchor: 0.5,
        align: 0.5,
        animationSpeed: 0.5,
        autoPlay: true,
    },
    { spritesheet: "explosion" },
);

await explosion.load();
canvas.add("explosion", explosion);

Compared to the Sprite component, AnimatedSprite adds the following features:

  • source: The description of the frames (spritesheet, animation, frames).
  • load: Method to load the frames described by source.
  • play and stop: Methods to play and pause the animation.
  • gotoAndPlay and gotoAndStop: Methods to jump to a frame.
  • setFrame: Like gotoAndPlay/gotoAndStop, but also works before the frames are loaded.
  • animationSpeed: The speed of the animation (1 = one frame per tick, at 60 fps).
  • loop: Indicates if the animation should restart after the last frame.
  • currentFrame, totalFrames and playing: The state of the animation.

Show

The simplest way to show an animation on the canvas is to use the showAnimatedSprite function. This function combines load and canvas.add, and starts playing the animation (pass autoPlay: false to start it stopped).

The function accepts two forms:

  • showAnimatedSprite(alias, options): the alias of the component is also the alias of the spritesheet.
  • showAnimatedSprite(alias, source, options): source is the alias (or URL) of a spritesheet, or an AnimatedSpriteSource. If source is undefined, or it has no spritesheet and no frames (for example { animation: "walk" }), the alias of the component is used as the alias of the spritesheet.

When only the spritesheet is set, all its frames are used, sorted in natural order (frame2 comes before frame10).

import { newLabel, showAnimatedSprite } from "@drincs/pixi-vn";

export const startLabel = newLabel("start", [
    async () => {
        // "explosion" is both the alias of the component and of the spritesheet
        await showAnimatedSprite("explosion", {
            anchor: 0.5,
            align: { x: 0.25, y: 0.5 },
            animationSpeed: 0.5,
        });
        // a different alias for the component
        await showAnimatedSprite("player", "fighter", {
            anchor: 0.5,
            align: { x: 0.75, y: 0.5 },
            animationSpeed: 0.4,
        });
    },
]);

Add

To add an animation to the canvas, use the addAnimatedSprite function. This function only adds the component to the canvas; it does not load its frames. Call load when you want to show it.

import { addAnimatedSprite, AnimatedSprite, canvas, newLabel } from "@drincs/pixi-vn";

export const startLabel = newLabel("start", [
    () => {
        addAnimatedSprite("fighter", {
            anchor: 0.5,
            align: 0.5,
            animationSpeed: 0.4,
        });
    },
    async () => {
        const fighter = canvas.find<AnimatedSprite>("fighter");
        if (fighter) {
            await fighter.load();
            fighter.play();
        }
    },
]);

Remove

As with other canvas components, you can remove this component using the canvas.remove function.

Play, pause and speed

Use play and stop to resume and pause the animation, animationSpeed to change its speed, and gotoAndStop / gotoAndPlay to jump to a frame.

import { AnimatedSprite, canvas, narration, newLabel, showAnimatedSprite } from "@drincs/pixi-vn";

export const startLabel = newLabel("start", [
    async () => {
        narration.dialogue = "Play the animation";
        await showAnimatedSprite("fighter", {
            anchor: 0.5,
            align: 0.5,
            animationSpeed: 0.4,
        });
    },
    () => {
        narration.dialogue = "Pause the animation";
        canvas.find<AnimatedSprite>("fighter")?.stop();
    },
    () => {
        narration.dialogue = "Resume the animation, slower";
        const fighter = canvas.find<AnimatedSprite>("fighter");
        if (fighter) {
            fighter.animationSpeed = 0.1;
            fighter.play();
        }
    },
    () => {
        narration.dialogue = "Go to frame 15 and stop";
        canvas.find<AnimatedSprite>("fighter")?.gotoAndStop(15);
    },
]);

To repeat the animation forever, keep loop set to true (the default). With loop: false the animation stops on its last frame.

Choose the frames

An AnimatedSpriteSource can select which frames to use:

  • { spritesheet, animation }: the frames of an animation defined in the animations field of the spritesheet JSON.
  • { spritesheet, frames }: the listed frames of the spritesheet, in the given order.
  • { frames }: without a spritesheet, each frame is the alias (or URL) of a separate image.

Each item of frames can also be an object { texture, time }, to set the duration of that frame in milliseconds.

import { newLabel, showAnimatedSprite } from "@drincs/pixi-vn";

export const startLabel = newLabel("start", [
    async () => {
        // Only some frames of the spritesheet, in the given order
        await showAnimatedSprite(
            "fighter",
            {
                spritesheet: "fighter",
                frames: ["rollSequence0000.png", "rollSequence0010.png", "rollSequence0020.png"],
            },
            { anchor: 0.5, align: { x: 0.25, y: 0.5 }, animationSpeed: 0.05 },
        );
        // Frames with a custom duration (in milliseconds)
        await showAnimatedSprite(
            "countdown",
            {
                spritesheet: "digits",
                frames: [
                    { texture: "0123456789 3.ase", time: 1000 },
                    { texture: "0123456789 2.ase", time: 1000 },
                    { texture: "0123456789 1.ase", time: 1000 },
                    { texture: "0123456789 0.ase", time: 2000 },
                ],
            },
            { anchor: 0.5, align: { x: 0.75, y: 0.5 }, scale: 3 },
        );
    },
]);

Frame durations (Aseprite)

Some tools, such as Aseprite and TexturePacker, store the duration (in milliseconds) of each frame in the spritesheet JSON. Set useFrameDurations: true to use these durations instead of a fixed speed. A frame without a duration lasts DEFAULT_ANIMATED_SPRITE_FRAME_TIME (100 ms). animationSpeed still works as a multiplier.

import { newLabel, showAnimatedSprite } from "@drincs/pixi-vn";

export const startLabel = newLabel("start", [
    async () => {
        // Each digit of this Aseprite export lasts 500 ms
        await showAnimatedSprite(
            "digits",
            { spritesheet: "digits", useFrameDurations: true },
            { anchor: 0.5, align: 0.5, scale: 3 },
        );
    },
]);

Events

To run some logic when the animation ends, restarts or changes frame, listen to these events with on:

  • "complete": the animation reached its last frame and stopped (only with loop: false). The listener receives the component.
  • "loop": the animation restarted from the first frame (only with loop: true). The listener receives the component.
  • "frameChange": the current frame changed. The listener receives the new frame index and the component.

As for the other canvas events, the listener must be registered with @eventDecorator, so it is saved and still works after loading a save or going back. The listeners are not called while the frames are loaded or a save is restored.

import { AnimatedSprite, canvas, eventDecorator, newLabel, showAnimatedSprite } from "@drincs/pixi-vn";

export class ExplosionEvents {
    @eventDecorator()
    static remove(component: AnimatedSprite) {
        canvas.remove(component.label);
    }
}

export const startLabel = newLabel("start", [
    async () => {
        const explosion = await showAnimatedSprite("explosion", { anchor: 0.5, align: 0.5, loop: false });
        // remove the explosion when the animation ends
        explosion.on("complete", ExplosionEvents.remove);
    },
]);

Save and history

The memory of an AnimatedSprite contains its source, currentFrame, playing, animationSpeed, loop and all the usual position properties. When a save is loaded or the player goes back, the frames are loaded again from the source.

  • The frames can only come from an AnimatedSpriteSource: you can't pass a Texture[], and AnimatedSprite.fromFrames/fromImages throw an error, because loaded textures can't be saved.
  • The onComplete, onFrameChange and onLoop callbacks of PixiJS are not saved. Use the events instead.

Use the frames in a custom component

If you are creating a custom component, getSpritesheet loads a spritesheet from its alias, and getAnimatedSpriteFrames turns an AnimatedSpriteSource into the frames of a PixiJS AnimatedSprite.

import { getAnimatedSpriteFrames } from "@drincs/pixi-vn";

const frames = await getAnimatedSpriteFrames({ spritesheet: "hero", animation: "walk" });

On this page