Open in a new tab

A small book of six numbered pages, shown two at a time, drawn in SVG with a page-curl fold. Turn pages with the Previous and Next buttons, or with the pointer: hovering a page corner peels it, pressing drags it, clicking turns it.

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

When to use it

A brochure, a catalogue, a product tour, a photo album: content that reads naturally as pages and where the turn itself is part of the experience.

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, pages.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

  • createPageflip(svgRoot, { pages, width, height, duration, spread, events }) builds the book into an SVG you provide (its viewBox is 0 0 800 560, two pages wide) and returns { instance, dispose }.
  • Each page is { id, template }, the template being a graphic.svgBuild node description. pages.js generates six, a coloured rect and a number, so no image file is loaded.
  • instance.next() and instance.previous() start a turn and return its timeline, or null at either end; instance.index and instance.pageCount are the readout. The page disables both buttons while a turn runs.
  • spread: true shows two pages side by side with the leaf crossing the spine. The events option takes fw's events module, which gives the pointer corners (peel, drag, click).
  • dispose() stops a turn still in flight before it removes the book.
  • Limits: the book has fixed content and a fixed 500 ms turn; single-page (non-spread) mode and page jumping are not shown.

Code

main.js

javascriptApache-2.053 lines

// SPDX-License-Identifier: Apache-2.0
import { events } from '@awacloud/fw/dom/query/events.js';
import { createPageflip } from '@awacloud/graphic-anim';
import { PAGE_HEIGHT, PAGE_WIDTH, buildPages } from './pages.js';

const el = (/** @type {string} */ id) => /** @type {HTMLElement} */ (document.getElementById(id));

/**
 * Build the book into the `<svg>` `mount` and wire the Previous / Next buttons and the page readout.
 * @param {SVGElement} mount an SVG root whose viewBox is 0 0 800 560 (two pages side by side)
 */
export function mountBook(mount) {
    const book = createPageflip(mount, {
        pages: buildPages(),
        width: PAGE_WIDTH,
        height: PAGE_HEIGHT,
        duration: 500,
        spread: true, // two pages side by side, the leaf crossing the spine
        events: events.factory(), // pointer corners: hover peels, a press drags, a click turns
    });
    const { instance } = book;
    /** @type {{ done: boolean }|null} the turn in flight, if any */
    let turning = null;
    let frame = 0;

    // Disable the buttons for the length of a turn (an overlapping click would be ignored anyway).
    const refresh = () => {
        if (!el('page-label')) return; // the page was replaced: stop following it
        if (turning?.done) turning = null;
        el('page-label').textContent = `${instance.index + 1} / ${instance.pageCount}`;
        /** @type {HTMLButtonElement} */ (el('prev')).disabled = Boolean(turning) || instance.index <= 0;
        const last = instance.index >= instance.pageCount - 1;
        /** @type {HTMLButtonElement} */ (el('next')).disabled = Boolean(turning) || last;
        frame = requestAnimationFrame(refresh);
    };
    const turn = (/** @type {'next'|'previous'} */ way) => () => { if (!turning) turning = instance[way](); };
    const onPrev = turn('previous');
    const onNext = turn('next');
    el('prev').addEventListener('click', onPrev);
    el('next').addEventListener('click', onNext);
    refresh();
    return {
        book,
        dispose() {
            cancelAnimationFrame(frame);
            el('prev').removeEventListener('click', onPrev);
            el('next').removeEventListener('click', onNext);
            book.dispose(); // stops a turn still in flight
        },
    };
}

export const flipbook = mountBook(/** @type {SVGElement} */ (document.getElementById('mount')));

index.html

htmlApache-2.030 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 · A page-turning book</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>A page-turning book</h1>
    <p>Six numbered pages shown two at a time. Use the buttons, or the page corners:
    hover peels one, a press drags it, a click turns it.</p>
    <p>Page <strong id="page-label"></strong></p>
    <svg id="mount" viewBox="0 0 800 560" role="img" aria-label="A book of six numbered pages"></svg>
    <p class="controls">
      <button id="prev" type="button">&larr; Previous</button>
      <button id="next" type="button">Next &rarr;</button>
    </p>
  </main>
</body>
</html>

pages.js

javascriptApache-2.036 lines

// SPDX-License-Identifier: Apache-2.0
// The book's content: six numbered pages generated in code, no image file.

export const PAGE_WIDTH = 400;
export const PAGE_HEIGHT = 560;
export const PAGE_COUNT = 6;

const hue = (/** @type {number} */ i) => (360 / PAGE_COUNT) * i;

/**
 * The six page specs `{ id, template }`; a template is a graphic.svgBuild description: a filled rect
 * of its own hue and the page number, centred.
 * @returns {Array<{ id: string, template: object }>}
 */
export function buildPages() {
    return Array.from({ length: PAGE_COUNT }, (_, i) => ({
        id: `page-${i + 1}`,
        template: {
            tag: 'g',
            children: [
                {
                    tag: 'rect',
                    attrs: { x: 0, y: 0, width: PAGE_WIDTH, height: PAGE_HEIGHT, fill: `hsl(${hue(i)}, 60%, 55%)` },
                },
                {
                    tag: 'text',
                    attrs: {
                        x: PAGE_WIDTH / 2, y: PAGE_HEIGHT / 2, 'text-anchor': 'middle', 'dominant-baseline': 'middle',
                        'font-size': 96, 'font-family': 'system-ui, sans-serif', fill: '#ffffff',
                    },
                    text: String(i + 1),
                },
            ],
        },
    }));
}

style.css

cssApache-2.04 lines

/* SPDX-License-Identifier: Apache-2.0 */
#mount { display: block; width: min(100%, 32.5rem); height: auto; }
.controls { display: flex; gap: 0.5rem; }
button:disabled { opacity: 0.5; cursor: default; }