VideoFrame
Un agente può pubblicare nei suoi dati un'immagine che cambia molte volte al secondo (il flusso di una fotocamera, quello che vede un robot o una simulazione). VideoFrame mostra quell'immagine come un video con un badge Live, il numero di fotogrammi ricevuti nell'ultimo secondo e un pulsante Pause che blocca l'immagine su un fotogramma. Usalo per una vista di un agente in stile YouTube o per un pannello in diretta in un mondo.
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' });L'agente finto pubblica dieci volte al secondo un nuovo data URI SVG in world.data.frame. Un agente vero pubblica allo stesso modo fotogrammi JPEG o PNG come data URI o URL. Finché non arriva il primo fotogramma il riquadro mostra "Waiting for the first frame…". Da lì in poi ogni nuovo fotogramma sostituisce il src di un unico <img>.
La versione in JavaScript semplice si iscrive solo a quella chiave con world.onData(name, listener). onData è il modo più leggero di seguire dati veloci perché il suo listener riceve ogni nuovo fotogramma e nessun altro cambiamento del mondo. La versione React invece legge world.data[name] a ogni cambiamento del mondo che useWorld le consegna (Segui i dati veloci senza rallentare e Prestazioni).
Mentre il video è in pausa l'immagine conserva il suo fotogramma e il contatore continua a contare i fotogrammi che arrivano. Resume torna a mostrare i fotogrammi in diretta.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo (o l'agente), da useWorld. |
name | (obbligatorio) | La chiave in world.data il cui valore (un data URI o un URL) cambia a ogni fotogramma. |
alt | (obbligatorio) | Il testo alt dell'immagine. |
Parametri
videoFrame(container, world, options) disegna il video dentro container e ne segue i fotogrammi con onData.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo (o l'agente), da connectToHost. |
options.name | La chiave dei fotogrammi in world.data. |
options.alt | Il testo alt dell'immagine. |
Restituisce una funzione che rimuove il listener di onData e il video.
Modificalo
- Schermo intero: chiama
stage.requestFullscreen()da un pulsante. La webapp permette lo schermo intero in ogni vista. Per un pannello a schermo intero che si chiude con il tasto indietro vediFullScreenPicture. - Salvare un fotogramma: lo salva un
<a>il cuihrefè il fotogramma corrente e il cui attributodownloadcontiene un nome di file (FileList). - Più telecamere: mostra in una griglia un
VideoFrameper ogni chiave dei dati. - Riproduzione più fluida: per mostrare molti fotogrammi al secondo su un telefono lento, disegnali su un canvas in
requestAnimationFramee salta quelli che arrivano fra due disegni.