Open in a new tab

A small SVG scene described as JSON: a traffic light whose three lamps fire named events (stop, warn, go) when clicked, each event running its own animations. The scene is data in scene.json; the page only builds it and wires the events.

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

When to use it

Illustrations and diagrams that react to input, where the structure and the animations should live in a file a designer can edit rather than in code.

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, scene.json 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

  • scene.createScene({ template, refs, events, prefix }) builds the SVG subtree from the template node description, and returns root, el(name) (the element bound to a refs name) and fire(eventName).
  • Each entry of events lists animations (target, property, from, to, duration) and a mode; firing the event plays them. go and stop run theirs in parallel, so one click lights a lamp and darkens the others at once.
  • scene.json has no prefix: graphic.scene defaults it to scene, so building the same spec twice in a document would collide on every id. The caller mints a fresh prefix per instance, as mountScene does.
  • The page reads scene.json with fetch and a top-level await, next to the page and on the same origin. A JSON import attribute also works in current browsers, but this folder's lint configuration does not parse it.
  • Every lamp is also reachable through a button that fires the same event, so the light does not need a pointer.
  • Limits: the three events are fixed in the JSON; there is no timer-driven cycle through the lights.

Code

main.js

javascriptApache-2.048 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { graphicModules } from '@awacloud/graphic-anim';

// The scene is content-as-data: scene.json is read next to the page (same origin, top-level await).
const spec = await (await fetch(new URL('./scene.json', import.meta.url))).json();
fw.runtime.registerAllDeep(graphicModules);
const { scene: sceneModule } = fw.runtime.resolve('graphic.anim');
let instance = 0;

/** The lamp that fires each named event: clicking a lamp is the same as pressing its button. */
export const EVENT_OF_LAMP = { red: 'stop', yellow: 'warn', green: 'go' };

/**
 * Build the traffic light into `mount` and wire its events to the lamps and to `buttons`.
 * @param {SVGElement} mount
 * @param {ParentNode} buttons holds `button[data-event]`, one per named event
 */
export function mountScene(mount, buttons) {
    // graphic.scene defaults its id prefix to 'scene' (the spec has none): mint a fresh one per instance.
    const scene = sceneModule.createScene({ ...spec, prefix: `scene-${instance++}` });
    mount.appendChild(scene.root);
    const off = [];
    for (const [lamp, name] of Object.entries(EVENT_OF_LAMP)) {
        const target = scene.el(lamp); // bound by reference once, from the built subtree
        target.style.cursor = 'pointer';
        const fire = () => scene.fire(name);
        target.addEventListener('click', fire);
        off.push(() => target.removeEventListener('click', fire));
    }
    for (const button of buttons.querySelectorAll('button[data-event]')) {
        const fire = () => scene.fire(/** @type {HTMLElement} */ (button).dataset.event);
        button.addEventListener('click', fire);
        off.push(() => button.removeEventListener('click', fire));
    }
    return {
        scene,
        dispose() {
            off.forEach((undo) => undo());
            scene.root.remove();
        },
    };
}

export const light = mountScene(
    /** @type {SVGElement} */ (document.getElementById('mount')),
    /** @type {HTMLElement} */ (document.getElementById('events')),
);

index.html

htmlApache-2.029 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 traffic light from a JSON scene</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 traffic light from a JSON scene</h1>
    <p>Click a lamp, or use the buttons: the yellow lamp fires warn, the green one go, the red one stop.</p>
    <svg id="mount" viewBox="0 0 80 160" role="img" aria-label="A traffic light with three lamps"></svg>
    <p id="events" class="controls">
      <button type="button" data-event="stop">Stop</button>
      <button type="button" data-event="warn">Warn</button>
      <button type="button" data-event="go">Go</button>
    </p>
  </main>
</body>
</html>

scene.json

jsonApache-2.041 lines

{
    "template": {
        "tag": "g",
        "children": [
            { "tag": "rect", "attrs": { "id": "housing", "x": 8, "y": 8, "width": 64, "height": 144, "rx": 10, "fill": "#20242c", "stroke": "#3a3f4a", "stroke-width": "2" } },
            { "tag": "circle", "attrs": { "id": "lamp-red", "cx": 40, "cy": 40, "r": 16, "fill": "#5a1414" } },
            { "tag": "circle", "attrs": { "id": "lamp-yellow", "cx": 40, "cy": 80, "r": 16, "fill": "#5a4c14" } },
            { "tag": "circle", "attrs": { "id": "lamp-green", "cx": 40, "cy": 120, "r": 16, "fill": "#145a1e" } }
        ]
    },
    "refs": {
        "red": "lamp-red",
        "yellow": "lamp-yellow",
        "green": "lamp-green"
    },
    "events": {
        "warn": {
            "at": "yellow",
            "animations": [
                { "target": "yellow", "property": "fill", "from": "#5a4c14", "to": "#ffdd33", "duration": 260 }
            ]
        },
        "go": {
            "at": "green",
            "mode": "parallel",
            "animations": [
                { "target": "red", "property": "fill", "from": "#ff3b3b", "to": "#5a1414", "duration": 260 },
                { "target": "yellow", "property": "fill", "from": "#ffdd33", "to": "#5a4c14", "duration": 260 },
                { "target": "green", "property": "fill", "from": "#145a1e", "to": "#33e04d", "duration": 260 }
            ]
        },
        "stop": {
            "at": "red",
            "mode": "parallel",
            "animations": [
                { "target": "green", "property": "fill", "from": "#33e04d", "to": "#145a1e", "duration": 260 },
                { "target": "red", "property": "fill", "from": "#5a1414", "to": "#ff3b3b", "duration": 260 }
            ]
        }
    }
}

style.css

cssApache-2.03 lines

/* SPDX-License-Identifier: Apache-2.0 */
#mount { display: block; width: 10rem; height: auto; }
.controls { display: flex; gap: 0.5rem; }