Skip to content

Follow the pictures of the camera ​

In step 1 every one of the ten frames a second went through subscribe and re-rendered the whole view. The camera now gets a listener of its own (onData) that renders each frame separately from the rest of the view, counts the frames and lets the person pause the camera.

Why the camera needs its own listener ​

subscribe calls its listener after every change of the agent (a new frame, a new message or a new status). With the camera these calls arrive ten times a second and never more than once per animation frame. Re-rendering a name and a description at that rate costs nothing. The next steps, however, add a conversation, the camera of the person and a message box. Rebuilding all of them ten times a second slows the view down and in plain JavaScript also loses the scroll position and the text selection of the person.

agent.onData(name, listener) calls listener with each new value of one name of data and ignores every other change. It returns a function that stops the listener:

js
const stop = agent.onData('camera', (frame) => {
  picture.src = frame;
  frames += 1;
});

// Later: stop following. The picture stays on the last frame.
stop();

Pause and play ​

Pause stops the listener with the function returned by onData and the <img> keeps showing the last frame. To resume, Play calls onData again:

js
function play() {
  stopCamera = agent.onData('camera', (frame) => { picture.src = frame; frames += 1; });
}

function pause() {
  stopCamera();
  stopCamera = null;
}

Count the pictures ​

The listener increments frames on each frame. Once a second a timer writes the count into the caption ("Live: 10 frames a second") and resets it to zero. From this count you and the person can tell whether the camera is live.

In plain JavaScript all the code of the camera has moved to the listener of onData and subscribe now renders only the title and the description.

In React ​

In React the camera is a component (AgentCamera) that registers its onData listener in an effect. Writing each frame into the <img> through a ref instead of storing it in state avoids one extra render per frame.

jsx
useEffect(() => {
  if (isPaused) return undefined;
  let frames = 0;
  const stop = agent.onData('camera', (frame) => {
    picture.current.src = frame;
    frames += 1;
  });
  const timer = setInterval(() => { setFramesPerSecond(frames); frames = 0; }, 1000);
  return () => {
    stop();
    clearInterval(timer);
  };
}, [isPaused]);
  • The effect runs again only when isPaused changes. The cleanup that runs on Pause stops both the onData listener and the timer.
  • agent is not a dependency on purpose. Because useWorld returns a new copy of agent on every change, listing it would stop and restart the listener on every frame. onData works from any copy and the first one is enough.

useWorld still re-renders your components on every change of the agent and therefore on every frame. These renders are cheap here because React updates in the DOM only what differs. They stay cheap as long as you keep heavy work out of them (Performance).

The code ​

jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
};

// The camera of the agent, apart from the rest, with its picture, a caption and a button to pause it.
function AgentCamera({ agent }) {
	const picture = useRef(null);
	const [isPaused, setIsPaused] = useState(false);
	const [framesPerSecond, setFramesPerSecond] = useState(null);

	useEffect(() => {
		if (isPaused) return undefined;
		let frames = 0;
		// onData calls this with every new picture of `camera`, and for nothing else.
		// The picture goes straight into the <img>, with no state and no new render.
		const stop = agent.onData('camera', (frame) => {
			picture.current.src = frame;
			frames += 1;
		});
		// Once a second, show how many pictures arrived.
		const timer = setInterval(() => {
			setFramesPerSecond(frames);
			frames = 0;
		}, 1000);
		// A pause stops both, and the picture stays on the last frame.
		return () => {
			stop();
			clearInterval(timer);
		};
		// Start again only after a pause, because `onData` works from any copy of `agent`.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isPaused]);

	let caption = `Live: ${framesPerSecond} frames a second`;
	if (isPaused) caption = 'Paused';
	else if (framesPerSecond === null) caption = `Waiting for ${agent.name}'s camera…`;
	return (
		<>
			<img ref={picture} alt={`${agent.name}'s camera`} width="320" height="180" />
			<p>{caption}</p>
			<button onClick={() => setIsPaused(!isPaused)}>{isPaused ? 'Play' : 'Pause'}</button>
		</>
	);
}

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	const { world: agent, error } = useWorld({ fake: { agent: feeder } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;
	return (
		<>
			<h1>{agent.name}</h1>
			<p>{agent.profile.description}</p>
			<AgentCamera agent={agent} />
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
};

// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: feeder } });

const title = document.createElement('h1');
const description = document.createElement('p');
document.body.append(title, description);

// Everything but the camera. This listener runs at every change, a new picture included, and must stay light.
agent.subscribe((node) => {
	title.textContent = node.name;
	description.textContent = node.profile.description ?? '';
});

// The camera, apart from the rest, with its picture, a caption and a button to pause it.
const picture = document.createElement('img');
picture.alt = `${agent.name}'s camera`;
picture.width = 320;
picture.height = 180;
const caption = document.createElement('p');
const pauseButton = document.createElement('button');
document.body.append(picture, caption, pauseButton);

let frames = 0; // pictures since the last count
let framesPerSecond = null; // the last count, or null before the first one
let stopCamera = null; // stops following the camera, or null while paused

function drawCaption() {
	if (!stopCamera) caption.textContent = 'Paused';
	else if (framesPerSecond === null) caption.textContent = `Waiting for ${agent.name}'s camera…`;
	else caption.textContent = `Live: ${framesPerSecond} frames a second`;
	pauseButton.textContent = stopCamera ? 'Pause' : 'Play';
}

function play() {
	// onData calls this with every new picture of `camera`, and for nothing else.
	stopCamera = agent.onData('camera', (frame) => {
		picture.src = frame;
		frames += 1;
	});
	drawCaption();
}

function pause() {
	stopCamera(); // the picture stays on the last frame
	stopCamera = null;
	drawCaption();
}

pauseButton.onclick = () => (stopCamera ? pause() : play());
play();

// Once a second, show how many pictures arrived.
setInterval(() => {
	if (stopCamera) framesPerSecond = frames;
	frames = 0;
	drawCaption();
}, 1000);
Live, on a fake world
Open

Pause stops the bird and the clock and Play starts them again.

Next steps ​

Feeder also answers messages and step 3: Talk with the agent adds the conversation to the view.

The recipe Follow fast data without slowing down applies onData to a sound meter that changes twenty times a second.

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.