A traffic light from a JSON scene
Build an SVG scene from a JSON spec and fire its named events from clicks on the lamps.
Apache-2.0Runs on this page
Package: @awacloud/graphic-anim
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
npm install @awacloud/fw @awacloud/graphic-anim- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/andnode_modules/@awacloud/graphic-anim/src/at/vendor/graphic-anim/(node serve.jsfrom the examples root does both; any static server works). - Copy
index.html,main.js,scene.jsonandstyle.cssnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link.
What it shows
scene.createScene({ template, refs, events, prefix })builds the SVG subtree from thetemplatenode description, and returnsroot,el(name)(the element bound to arefsname) andfire(eventName).- Each entry of
eventslists animations (target,property,from,to,duration) and amode; firing the event plays them.goandstoprun theirs in parallel, so one click lights a lamp and darkens the others at once. scene.jsonhas noprefix:graphic.scenedefaults it toscene, so building the same spec twice in a document would collide on every id. The caller mints a fresh prefix per instance, asmountScenedoes.- The page reads
scene.jsonwithfetchand a top-levelawait, 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
// 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
<!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
{
"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
/* SPDX-License-Identifier: Apache-2.0 */
#mount { display: block; width: 10rem; height: auto; }
.controls { display: flex; gap: 0.5rem; }