Open in a new tab

A discrete frame sequence: eight regular polygons generated in code, one more side than the last (a triangle up to a decagon), shown one at a time like a flip book. Play, pause, restart or jump to any frame.

Uses @awacloud/graphic-anim (Apache-2.0). This example's code is Apache-2.0.

When to use it

Frame-by-frame animation that is not a smooth tween: a sprite flip, a loading indicator, a step-through explainer. For continuous motion, see graphic-anim/engine.

Copy-paste steps

  1. npm install @awacloud/fw @awacloud/graphic-anim
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ and node_modules/@awacloud/graphic-anim/src/ at /vendor/graphic-anim/ (node serve.js from the examples root does both; any static server works).
  3. Copy index.html, main.js, polygons.js and style.css next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

What it shows

  • frames.frames({ frames, fps, loop }) wraps already-built elements in a sequence. In its discrete mode the default display writer shows exactly one of them at a time, by setting the display attribute.
  • play(), pause() and seek(index) drive it; seek clamps and does not throw, and it renders the frame without playing, so the stage is never blank before the first Play.
  • The readout under the title reads the sequence's own frame and playing properties on every animation frame: the page keeps no copy of that state.
  • The frames come from polygons.js: node descriptions built with svgBuild.build, bound to the sequence by reference. No image file is loaded.
  • Limits: the sequence plays at a fixed 4 frames per second and loops; the sprite mode of graphic.frames is not shown here.

Code

main.js

javascriptApache-2.050 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { graphicModules } from '@awacloud/graphic-anim';
import { FRAME_COUNT, frameDesc } from './polygons.js';

fw.runtime.registerAllDeep(graphicModules);
const { svgBuild, frames } = fw.runtime.resolve('graphic.anim');
const el = (/** @type {string} */ id) => /** @type {HTMLElement} */ (document.getElementById(id));

/** @type {{ frame: number, frameCount: number, playing: boolean, play(): void, pause(): void }} */
let sequence;
let poll = 0;

/** Show the live `frame` and `playing` of the sequence (no shadow copy) and mark the current jump button. */
export function readout() {
    el('frame-label').textContent = `${sequence.frame + 1} / ${sequence.frameCount}`;
    el('playing-label').textContent = sequence.playing ? 'playing' : 'paused';
    for (const button of el('frame-jump').children) {
        button.setAttribute('aria-current', String(Number(button.textContent) - 1 === sequence.frame));
    }
}

/** (Re)build the polygons, park the sequence on frame 0, paused, and rebuild the jump buttons. */
export function start() {
    cancelAnimationFrame(poll);
    sequence?.pause();
    const mount = el('mount');
    mount.replaceChildren();
    const elements = Array.from({ length: FRAME_COUNT }, (_, i) => mount.appendChild(svgBuild.build(frameDesc(i))));
    // Discrete mode with the default `display` writer: exactly one frame is visible at a time.
    sequence = frames.frames({ frames: elements, fps: 4, loop: true });
    sequence.seek(0); // visible before Play, never a blank or overlapping stage
    el('frame-jump').replaceChildren(...elements.map((_, i) => {
        const button = Object.assign(document.createElement('button'), { type: 'button', textContent: String(i + 1) });
        button.addEventListener('click', () => { sequence.seek(i); readout(); });
        return button;
    }));
    // Follow until the page's readout is gone (another page replaced the document body).
    const follow = () => {
        if (!document.getElementById('frame-label')) return;
        readout();
        poll = requestAnimationFrame(follow);
    };
    follow();
}

el('play').addEventListener('click', () => { sequence.play(); readout(); });
el('pause').addEventListener('click', () => { sequence.pause(); readout(); });
el('restart').addEventListener('click', start);
start();

index.html

htmlApache-2.032 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>graphic-anim · Flip through a frame sequence</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <link rel="stylesheet" href="./style.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
    "@awacloud/graphic-anim": "/vendor/graphic-anim/main.js", "@awacloud/graphic-anim/": "/vendor/graphic-anim/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Flip through a frame sequence</h1>
    <p>Eight regular polygons, one more side each, shown one at a time like the pages of a flip book.</p>
    <p>Frame <strong id="frame-label"></strong>, <span id="playing-label"></span></p>
    <svg id="mount" viewBox="0 0 100 100" role="img" aria-label="A polygon with three to ten sides"></svg>
    <p class="controls">
      <button id="play" type="button">Play</button>
      <button id="pause" type="button">Pause</button>
      <button id="restart" type="button">Restart</button>
    </p>
    <p id="jump-title">Jump to frame</p>
    <div id="frame-jump" role="group" aria-labelledby="jump-title"></div>
  </main>
</body>
</html>

polygons.js

javascriptApache-2.037 lines

// SPDX-License-Identifier: Apache-2.0
// The frames of the sequence, generated in code (no image assets): regular polygons with one more side each.

/** Frames in the sequence: the first is a triangle, the last a decagon. */
export const FRAME_COUNT = 8;
const MIN_SIDES = 3;
const CENTER = 50;
const RADIUS = 42;

/** The `points` attribute of a regular polygon with `sides` sides, a vertex at the top. @param {number} sides */
export function polygonPoints(sides) {
    const points = [];
    for (let k = 0; k < sides; k += 1) {
        const theta = (Math.PI * 2 * k) / sides - Math.PI / 2;
        const [x, y] = [Math.cos(theta), Math.sin(theta)].map((unit) => (CENTER + RADIUS * unit).toFixed(2));
        points.push(`${x},${y}`);
    }
    return points.join(' ');
}

/**
 * The svgBuild description of frame `index`: a polygon in a group, its hue stepping across the sequence.
 * @param {number} index
 */
export function frameDesc(index) {
    const hue = Math.round((360 / FRAME_COUNT) * index);
    return {
        tag: 'g',
        children: [{
            tag: 'polygon',
            attrs: {
                points: polygonPoints(MIN_SIDES + index),
                fill: `hsl(${hue}, 70%, 55%)`, stroke: '#1a1a1a', 'stroke-width': 1.5,
            },
        }],
    };
}

style.css

cssApache-2.04 lines

/* SPDX-License-Identifier: Apache-2.0 */
#mount { display: block; width: min(100%, 18rem); height: auto; background: #1a1a1a; border-radius: 8px; }
#frame-jump { display: flex; flex-wrap: wrap; gap: 0.5rem; }
#frame-jump button[aria-current="true"] { font-weight: bold; outline: 2px solid var(--ex-accent, #2563eb); }