An analog clock on the real time
A three-hand analog clock built from a scene template, its hands tweened at the true clock rate.
Apache-2.0Runs on this page
Package: @awacloud/graphic-anim
An analog clock drawn as SVG: a dial built from a scene template and three hands that sweep continuously at the true clock rate, started from the current time.
Uses @awacloud/graphic-anim (Apache-2.0). This example's code is Apache-2.0.
When to use it
A live dial, gauge or any shape that turns around a point at a rate tied to
real time. For a one-shot move or colour change, see graphic-anim/engine.
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,template.jsandstyle.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
fw.runtime.registerAllDeep(graphicModules)registers the package's modules; resolvinggraphic.animgives the aggregate (scene,tween,scheduler,svgApply, and the rest) in one object.scene.createScene({ template, prefix, refs, events })builds the dial from a plain node description (template.js) and returns the elements bound by name throughrefs, so no per-tick lookup is needed. The id prefix defaults toscene: mint a fresh one for every instance, asmountClockdoes.- Each hand is a linear
Tweenover one exact clock cycle (60 s, 1 h, 12 h) of a plain number from 0 to 360, written by a customapplyas arotate(angle, cx, cy)transform. The tween interpolator ignores the pivot of arotate()string, so animating the string would turn the hand around the wrong point. graphic.tweenhas no repeat flag: on completion the tween restarts itself with the same range, which never drifts because the period is an exact cycle.dispose()removes each running tween from the shared scheduler, so no entry keeps the animation loop alive.- Limits: the dial has no tick marks or numerals, and the time shown is the visitor's local time at load; the hands are not re-synchronised afterwards.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { graphicModules } from '@awacloud/graphic-anim';
import { PIVOT, TEMPLATE } from './template.js';
fw.runtime.registerAllDeep(graphicModules);
const { scene: sceneModule, tween: tweenModule, svgApply, scheduler } = fw.runtime.resolve('graphic.anim');
/** Full-sweep period of each hand, in ms: one exact clock cycle, so a restart with the same range never drifts. */
export const PERIODS = { seconds: 60e3, minutes: 3600e3, hours: 43200e3 };
let instance = 0;
/** Each hand's angle in degrees clockwise from 12 o'clock, in floating point so the sweep is continuous. */
export function currentAngles(now = new Date()) {
const seconds = now.getSeconds() + now.getMilliseconds() / 1000;
const minutes = now.getMinutes() + seconds / 60;
const hours = (now.getHours() % 12) + minutes / 60;
return { seconds: seconds * 6, minutes: minutes * 6, hours: hours * 30 };
}
/** The pivoted transform of a hand. graphic.interpolate ignores a rotate() pivot, so the angle is written by hand. */
export const rotation = (/** @type {number} */ angle) => `rotate(${angle}, ${PIVOT.x}, ${PIVOT.y})`;
/**
* Build the dial into `mount` and start the three hands.
* @param {SVGElement} mount
* @returns {{ dispose(): void }}
*/
export function mountClock(mount) {
// graphic.scene defaults its id prefix to 'scene': mint a fresh one per instance.
const scene = sceneModule.createScene({
template: TEMPLATE, prefix: `clock-${instance++}`,
refs: { seconds: 'aTimeSeconds', minutes: 'aTimeMinutes', hours: 'aTimeHours' }, events: {},
});
mount.appendChild(scene.root);
const running = new Set();
let stopped = false;
const angles = currentAngles();
// A linear tween sweeps a plain number 0 -> 360 over one real cycle; `apply` turns it into the pivoted
// transform. graphic.tween has no repeat flag, so the tween restarts itself with the same range.
function spin(/** @type {SVGElement} */ target, /** @type {number} */ start, /** @type {number} */ period) {
svgApply.svgAttr(target, 'transform', rotation(start));
const cycle = () => {
if (stopped) return;
const sweep = new tweenModule.Tween({
target, property: 'transform', from: 0, to: 360, duration: period, easing: 'linear',
apply: (/** @type {number} */ deg) => {
svgApply.svgAttr(target, 'transform', rotation((start + deg) % 360));
},
onComplete: () => { running.delete(sweep); cycle(); },
});
running.add(sweep);
sweep.play();
};
cycle();
}
for (const name of /** @type {const} */ (['seconds', 'minutes', 'hours'])) {
spin(scene.el(name), angles[name], PERIODS[name]);
}
return {
dispose() {
stopped = true;
// A `stopped` flag alone would leave each tween scheduled: remove it from the scheduler.
for (const sweep of running) scheduler.scheduler.remove(sweep);
running.clear();
scene.root.remove();
},
};
}
mountClock(/** @type {SVGElement} */ (document.getElementById('mount')));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 · An analog clock on the real time</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>An analog clock on the real time</h1>
<p>A dial built from a scene template, with three hands that sweep continuously at the true clock rate.</p>
<svg id="mount" viewBox="0 0 800 800" role="img" aria-label="An analog clock showing the current time"></svg>
</main>
</body>
</html>template.js
// SPDX-License-Identifier: Apache-2.0
// The dial as a graphic.svgBuild node description, consumed by graphic.scene as its `template`.
// The ids are what `refs` binds the three hands by; graphic.scene prefixes them per instance.
/** The rotation pivot shared by the three hands: the centre of the 800 x 800 dial. */
export const PIVOT = { x: 400, y: 400 };
/** @param {string} id @param {string} stroke @param {number} width @param {number} top the hand's far end */
const hand = (id, stroke, width, top) => ({
tag: 'line', attrs: { id, stroke, 'stroke-width': width, x1: 400, y1: 400, x2: 400, y2: top },
});
export const TEMPLATE = {
tag: 'g',
children: [
{
tag: 'defs',
children: [
{ tag: 'mask', attrs: { id: 'aMaskClock' }, children: [
{ tag: 'circle', attrs: { fill: '#ffffff', cx: 100, cy: 100, r: 450 } }] },
{ tag: 'mask', attrs: { id: 'aMaskBackground' }, children: [
{ tag: 'rect', attrs: { fill: '#ffffff', x: 0, y: 0, width: 800, height: 800 } }] },
],
},
{
tag: 'g',
attrs: { mask: 'url(#aMaskBackground)' },
children: [
{ tag: 'rect', attrs: { id: 'aBackground', fill: '#da8028', x: 0, y: 0, width: 800, height: 800 } },
{
tag: 'circle',
attrs: { id: 'aClockBorder', fill: '#ffffff', opacity: 0.75, cx: 400, cy: 400, r: 400 },
},
{ tag: 'circle', attrs: { id: 'aClockBackground', fill: '#333333', cx: 400, cy: 400, r: 390 } },
hand('aTimeHours', '#dddddd', 2, 35),
hand('aTimeMinutes', '#dddddd', 2, 25),
hand('aTimeSeconds', '#ff3333', 1.5, 15),
{
tag: 'circle',
attrs: {
id: 'aClockEffect', fill: '#ffffff', mask: 'url(#aMaskClock)', opacity: 0.25,
cx: 400, cy: 400, r: 400,
},
},
],
},
],
};style.css
/* SPDX-License-Identifier: Apache-2.0 */
#mount { display: block; width: min(100%, 20rem); height: auto; margin-inline: auto; }