VideoFrame
An agent can publish in its data an image that changes many times a second (the stream of a camera, what a robot sees or a simulation). VideoFrame renders that image as a video with a Live badge, the number of frames received in the last second and a Pause button that freezes the image on one frame. Use it for a YouTube-like view of an agent or for a live panel in a world.
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/**
* VideoFrame: pictures that change many times a second, like a camera or a
* simulation, shown as a video with a "Live" mark, how many frames arrive
* each second and a button to pause on one frame.
* @param {object} props
* @param {object} props.world - The world (or agent), from useWorld.
* @param {string} props.name - The name of the frames in `world.data`: an image source, new at every frame.
* @param {string} props.alt - What the video shows, for people who cannot see it.
*/
export function VideoFrame({ world, name, alt }) {
const frame = world.data[name];
// The frame the person paused on, or null while it plays.
const [pausedOn, setPausedOn] = useState(null);
// When the last frames arrived, to count them each second.
const arrivals = useRef([]);
const [perSecond, setPerSecond] = useState(0);
useEffect(() => {
if (!frame) return;
const now = Date.now();
arrivals.current = [...arrivals.current.filter((time) => time > now - 1000), now];
setPerSecond(arrivals.current.length);
}, [frame]);
const shown = pausedOn ?? frame;
const box = { width: '100%', aspectRatio: '16 / 9', borderRadius: 14, background: '#000' };
return (
<div style={{ display: 'grid', gap: 8, maxWidth: 480 }}>
<div style={{ position: 'relative' }}>
{shown
? <img src={shown} alt={alt} style={{ ...box, display: 'block', objectFit: 'contain' }} />
: <div style={{ ...box, display: 'grid', placeItems: 'center', color: '#fff' }}>Waiting for the first frame…</div>}
<span style={{ position: 'absolute', top: 10, left: 10, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '2px 10px', borderRadius: 30, fontSize: 13, fontWeight: 600, color: '#fff', background: 'rgba(0, 0, 0, 0.6)' }}>
<span aria-hidden="true" style={{ width: 8, height: 8, borderRadius: '50%', background: pausedOn ? '#F0A54E' : '#E5453A' }} />
{pausedOn ? 'Paused' : 'Live'}
</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<button type="button" disabled={!frame} onClick={() => setPausedOn(pausedOn ? null : frame)}>{pausedOn ? 'Resume' : 'Pause'}</button>
<span style={{ fontSize: 13, opacity: 0.7 }}>{perSecond} frames a second</span>
</div>
</div>
);
}
// Using it, on a fake agent.
/**
* Draws one frame at a moment, as an SVG image source: a ball crossing the
* picture, and the time.
* @param {number} time - The time (Unix ms).
* @returns {string} The image source.
*/
function frameAt(time) {
const x = 20 + ((time / 10) % 280);
const clock = new Date(time).toLocaleTimeString();
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#1E3E96"/>
<circle cx="${x}" cy="90" r="20" fill="#F0A54E"/>
<text x="300" y="166" fill="#fff" font-family="sans-serif" font-size="14" text-anchor="end">${clock}</text></svg>`;
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}
// A fake agent to build with: a new frame ten times a second.
const camera = {
name: 'Camera',
data: { frame: { every: 100, value: frameAt } },
};
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { agent: camera } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return <VideoFrame world={world} name="frame" alt="The camera's picture: a ball crossing a blue room" />;
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/**
* Draws pictures that change many times a second (a camera, a simulation)
* into `container` as a video, with a "Live" mark, how many frames arrive each
* second and a button to pause on one frame. It follows only that name of the
* data with `onData`, to keep the rest of the world from slowing it down.
* @param {HTMLElement} container - Where to draw it.
* @param {object} world - The world (or agent), from connectToHost.
* @param {{name: string, alt: string}} options - The name of the frames in `world.data` (an image
* source, new at every frame), and what the video shows, for people who cannot see it.
* @returns {() => void} Stops following the frames and removes what it drew.
*/
export function videoFrame(container, world, { name, alt }) {
const box = { width: '100%', aspectRatio: '16 / 9', borderRadius: '14px', background: '#000' };
const wrap = document.createElement('div');
Object.assign(wrap.style, { display: 'grid', gap: '8px', maxWidth: '480px' });
const stage = document.createElement('div');
stage.style.position = 'relative';
const picture = document.createElement('img');
picture.alt = alt;
Object.assign(picture.style, box, { display: 'none', objectFit: 'contain' });
const waiting = document.createElement('div');
waiting.textContent = 'Waiting for the first frame…';
Object.assign(waiting.style, box, { display: 'grid', placeItems: 'center', color: '#fff' });
const badge = document.createElement('span');
Object.assign(badge.style, { position: 'absolute', top: '10px', left: '10px', display: 'inline-flex', alignItems: 'center', gap: '6px', padding: '2px 10px', borderRadius: '30px', fontSize: '13px', fontWeight: '600', color: '#fff', background: 'rgba(0, 0, 0, 0.6)' });
const dot = document.createElement('span');
dot.setAttribute('aria-hidden', 'true');
Object.assign(dot.style, { width: '8px', height: '8px', borderRadius: '50%' });
const badgeText = document.createElement('span');
badge.append(dot, badgeText);
stage.append(picture, waiting, badge);
const bar = document.createElement('div');
Object.assign(bar.style, { display: 'flex', alignItems: 'center', gap: '12px' });
const pause = document.createElement('button');
pause.type = 'button';
pause.disabled = true;
const rate = document.createElement('span');
Object.assign(rate.style, { fontSize: '13px', opacity: '0.7' });
rate.textContent = '0 frames a second';
bar.append(pause, rate);
wrap.append(stage, bar);
container.append(wrap);
let isPaused = false;
// When the last frames arrived, to count them each second.
let arrivals = [];
const drawBadge = () => {
badgeText.textContent = isPaused ? 'Paused' : 'Live';
dot.style.background = isPaused ? '#F0A54E' : '#E5453A';
pause.textContent = isPaused ? 'Resume' : 'Pause';
};
pause.onclick = () => {
isPaused = !isPaused;
drawBadge();
};
/** Shows a new frame (unless paused), and counts it. */
const show = (frame) => {
if (!frame) return;
const now = Date.now();
arrivals = [...arrivals.filter((time) => time > now - 1000), now];
rate.textContent = `${arrivals.length} frames a second`;
pause.disabled = false;
if (isPaused) return;
picture.src = frame;
picture.style.display = 'block';
waiting.style.display = 'none';
};
drawBadge();
show(world.get().data[name]);
// Called only with each new value of this name, the fastest way to follow frames.
const stop = world.onData(name, show);
return () => {
stop();
wrap.remove();
};
}
// Using it, on a fake agent.
/**
* Draws one frame at a moment, as an SVG image source: a ball crossing the
* picture, and the time.
* @param {number} time - The time (Unix ms).
* @returns {string} The image source.
*/
function frameAt(time) {
const x = 20 + ((time / 10) % 280);
const clock = new Date(time).toLocaleTimeString();
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#1E3E96"/>
<circle cx="${x}" cy="90" r="20" fill="#F0A54E"/>
<text x="300" y="166" fill="#fff" font-family="sans-serif" font-size="14" text-anchor="end">${clock}</text></svg>`;
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}
// A fake agent to build with: a new frame ten times a second.
const camera = {
name: 'Camera',
data: { frame: { every: 100, value: frameAt } },
};
// While building: the fake agent. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { agent: camera } });
const place = document.createElement('div');
document.body.append(place);
videoFrame(place, world, { name: 'frame', alt: 'The camera\'s picture: a ball crossing a blue room' });The fake agent publishes a new SVG data URI in world.data.frame ten times a second. A real agent publishes JPEG or PNG frames as data URIs or URLs in the same way. Until the first frame arrives the box reads "Waiting for the first frame…". Each new frame then replaces the src of a single <img>.
The plain JavaScript version subscribes to that key alone with world.onData(name, listener). onData is the lightest way to follow fast data because its listener receives each new frame and no other change of the world. The React version, on the other hand, reads world.data[name] at every change of the world that useWorld delivers (Follow fast data without slowing down and Performance).
While the video is paused the image keeps its frame and the counter keeps counting the frames that arrive. Resume shows the live frames again.
Props
| Prop | Default | What it is |
|---|---|---|
world | (required) | The world (or agent), from useWorld. |
name | (required) | The key in world.data whose value (a data URI or URL) changes at every frame. |
alt | (required) | The alt text of the image. |
Parameters
videoFrame(container, world, options) draws the video into container and follows its frames with onData.
| Parameter | What it is |
|---|---|
container | The element to draw into. |
world | The world (or agent), from connectToHost. |
options.name | The key of the frames in world.data. |
options.alt | The alt text of the image. |
It returns a function that removes the onData listener and the video.
Change it
- Full screen: call
stage.requestFullscreen()from a button. The webapp allows full screen in every view. For a full-screen panel closed by the back button, seeFullScreenPicture. - Save a frame: an
<a>whosehrefis the current frame and whosedownloadattribute holds a file name saves it (FileList). - Several cameras: render one
VideoFrameper key of the data in a grid. - Smoother playback: to show many frames a second on a slow phone, draw them on a canvas in
requestAnimationFrameand skip the frames that arrive between two paints.