Skip to content

Camera ​

An agent that reads a document, a game played with gestures and a photo booth all need a picture of what the person shows. Camera renders a Turn on the camera button that turns on the camera of the person and shows its live video. With an onPhoto callback it adds a Take a photo button that captures the current frame and passes it to onPhoto. Your callback can then send the photo to the world or the agent.

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

// The component: copy this part.

/**
 * Says in words why the camera did not start.
 * @param {Error} error - What `askFor` or `getUserMedia` failed with.
 * @returns {{text: string, canRetry: boolean}} The words, and whether trying again can help.
 */
function cameraProblem(error) {
	// The person said no in the webapp. Do not ask again, because the answer stays no while the view is shown.
	if (error.code === 'declined') return { text: 'You chose not to let this view use the camera.', canRetry: false };
	if (error.name === 'NotAllowedError') return { text: 'The browser did not allow the camera. Allow it in the browser\'s settings for this site, then try again.', canRetry: true };
	if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return { text: 'No camera was found on this device.', canRetry: true };
	if (error.name === 'NotReadableError') return { text: 'The camera is busy in another app. Close it, then try again.', canRetry: true };
	return { text: 'The camera could not start.', canRetry: true };
}

/**
 * Camera: the person's camera, shown in the view after they ask for it.
 * When you pass `onPhoto`, a button takes a photo of what the camera sees.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {(image: string) => void} [props.onPhoto] - Gets each photo, as an image source (JPEG data URI).
 * @param {'user'|'environment'} [props.facing='user'] - The front camera ('user') or the back one ('environment').
 */
export function Camera({ world, onPhoto, facing = 'user' }) {
	// 'off', 'starting', 'on' or 'failed'.
	const [state, setState] = useState('off');
	const [problem, setProblem] = useState(null);
	const streamRef = useRef(null);
	const videoRef = useRef(null);

	const stopCamera = () => {
		streamRef.current?.getTracks().forEach((track) => track.stop());
		streamRef.current = null;
	};
	// The camera stops when the component goes away.
	useEffect(() => stopCamera, []);
	// Once the video is on the page, it shows the camera.
	useEffect(() => {
		if (state === 'on') videoRef.current.srcObject = streamRef.current;
	}, [state]);

	const start = async () => {
		setState('starting');
		try {
			// The webapp asks the person first, for this view only. After a yes, it loads the view
			// again with the camera allowed. `webapp.allowed` then has it, and this line goes straight on.
			if (!world.webapp.allowed.includes('camera')) await world.askFor(['camera']);
			if (!navigator.mediaDevices?.getUserMedia) throw new Error('This browser has no camera here');
			streamRef.current = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facing }, audio: false });
			setState('on');
		} catch (error) {
			setProblem(cameraProblem(error));
			setState('failed');
		}
	};

	const turnOff = () => {
		stopCamera();
		setState('off');
	};

	const takePhoto = () => {
		// Draws what the video shows now on a canvas, at most 640 pixels wide, and gives it as a JPEG.
		const video = videoRef.current;
		const scale = Math.min(1, 640 / video.videoWidth);
		const canvas = document.createElement('canvas');
		canvas.width = Math.round(video.videoWidth * scale);
		canvas.height = Math.round(video.videoHeight * scale);
		canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
		onPhoto(canvas.toDataURL('image/jpeg', 0.85));
	};

	const box = { width: '100%', maxWidth: 480, aspectRatio: '4 / 3', borderRadius: 14, background: 'rgba(127, 127, 127, 0.15)' };
	return (
		<div style={{ display: 'grid', gap: 8, justifyItems: 'start' }}>
			{state === 'on' ? (
				// The front camera is shown as a mirror, as people expect, but the photo is not mirrored.
				<video ref={videoRef} autoPlay playsInline muted aria-label="Your camera"
					style={{ ...box, display: 'block', objectFit: 'cover', background: '#000', transform: facing === 'user' ? 'scaleX(-1)' : 'none' }} />
			) : (
				<div role="status" style={{ ...box, boxSizing: 'border-box', display: 'grid', placeItems: 'center', padding: 16, textAlign: 'center' }}>
					{state === 'off' && 'The camera is off.'}
					{state === 'starting' && 'Starting the camera…'}
					{state === 'failed' && problem.text}
				</div>
			)}
			<div style={{ display: 'flex', gap: 8 }}>
				{state === 'off' && <button type="button" onClick={start}>Turn on the camera</button>}
				{state === 'failed' && problem.canRetry && <button type="button" onClick={start}>Try again</button>}
				{state === 'on' && onPhoto && <button type="button" onClick={takePhoto}>Take a photo</button>}
				{state === 'on' && <button type="button" onClick={turnOff}>Turn off</button>}
			</div>
		</div>
	);
}

// Using it, on a fake agent.

// A fake agent to build with: it answers the photos it gets.
const lens = {
	name: 'Lens',
	onMessage: (message) => (message.image ? 'Thanks: I got your photo.' : 'Send me a photo.'),
};

export default function App() {
	// While building: the fake agent (every browser feature counts as allowed). In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { agent: lens } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	const answer = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<div style={{ display: 'grid', gap: 12, maxWidth: 360 }}>
			<h2 style={{ margin: 0 }}>{world.name}</h2>
			<p style={{ margin: 0 }}>{answer ? answer.text : 'Take a photo and Lens will get it.'}</p>
			<Camera world={world} onPhoto={(image) => world.send({ image, text: 'A photo' })} />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/**
 * Says in words why the camera did not start.
 * @param {Error} error - What `askFor` or `getUserMedia` failed with.
 * @returns {{text: string, canRetry: boolean}} The words, and whether trying again can help.
 */
function cameraProblem(error) {
	// The person said no in the webapp. Do not ask again, because the answer stays no while the view is shown.
	if (error.code === 'declined') return { text: 'You chose not to let this view use the camera.', canRetry: false };
	if (error.name === 'NotAllowedError') return { text: 'The browser did not allow the camera. Allow it in the browser\'s settings for this site, then try again.', canRetry: true };
	if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return { text: 'No camera was found on this device.', canRetry: true };
	if (error.name === 'NotReadableError') return { text: 'The camera is busy in another app. Close it, then try again.', canRetry: true };
	return { text: 'The camera could not start.', canRetry: true };
}

/**
 * Draws the person's camera into `container`, after they ask for it. When you
 * pass `onPhoto`, a button takes a photo of what the camera sees.
 * @param {HTMLElement} container - Where to draw it.
 * @param {object} world - The world, from connectToHost.
 * @param {{onPhoto?: (image: string) => void, facing?: 'user'|'environment'}} [options] - What gets each
 *   photo (an image source, a JPEG data URI), and the front camera ('user') or the back one ('environment').
 * @returns {() => void} Turns the camera off and removes what it drew.
 */
export function camera(container, world, { onPhoto, facing = 'user' } = {}) {
	const box = { width: '100%', maxWidth: '480px', aspectRatio: '4 / 3', borderRadius: '14px', background: 'rgba(127, 127, 127, 0.15)' };
	const wrap = document.createElement('div');
	Object.assign(wrap.style, { display: 'grid', gap: '8px', justifyItems: 'start' });
	// The front camera is shown as a mirror, as people expect, but the photo is not mirrored.
	const video = document.createElement('video');
	video.autoplay = true;
	video.playsInline = true;
	video.muted = true;
	video.setAttribute('aria-label', 'Your camera');
	Object.assign(video.style, box, { objectFit: 'cover', background: '#000', transform: facing === 'user' ? 'scaleX(-1)' : 'none' });
	const message = document.createElement('div');
	message.setAttribute('role', 'status');
	Object.assign(message.style, box, { boxSizing: 'border-box', placeItems: 'center', padding: '16px', textAlign: 'center' });
	const buttons = document.createElement('div');
	Object.assign(buttons.style, { display: 'flex', gap: '8px' });
	wrap.append(video, message, buttons);
	container.append(wrap);

	let stream = null;

	/** Makes a button. */
	const button = (text, onClick) => {
		const element = document.createElement('button');
		element.type = 'button';
		element.textContent = text;
		element.onclick = onClick;
		return element;
	};

	/** Shows one of the states: 'off', 'starting', 'on' or 'failed' (with its problem). */
	const show = (state, problem = null) => {
		video.style.display = state === 'on' ? 'block' : 'none';
		message.style.display = state === 'on' ? 'none' : 'grid';
		if (state === 'off') message.textContent = 'The camera is off.';
		if (state === 'starting') message.textContent = 'Starting the camera…';
		if (state === 'failed') message.textContent = problem.text;
		buttons.replaceChildren();
		if (state === 'off') buttons.append(button('Turn on the camera', start));
		if (state === 'failed' && problem.canRetry) buttons.append(button('Try again', start));
		if (state === 'on' && onPhoto) buttons.append(button('Take a photo', takePhoto));
		if (state === 'on') buttons.append(button('Turn off', turnOff));
	};

	const stopCamera = () => {
		stream?.getTracks().forEach((track) => track.stop());
		stream = null;
		video.srcObject = null;
	};

	async function start() {
		show('starting');
		try {
			// The webapp asks the person first, for this view only. After a yes, it loads the view
			// again with the camera allowed. `webapp.allowed` then has it, and this line goes straight on.
			if (!world.get().webapp.allowed.includes('camera')) await world.askFor(['camera']);
			if (!navigator.mediaDevices?.getUserMedia) throw new Error('This browser has no camera here');
			stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facing }, audio: false });
			video.srcObject = stream;
			show('on');
		} catch (error) {
			show('failed', cameraProblem(error));
		}
	}

	function turnOff() {
		stopCamera();
		show('off');
	}

	function takePhoto() {
		// Draws what the video shows now on a canvas, at most 640 pixels wide, and gives it as a JPEG.
		const scale = Math.min(1, 640 / video.videoWidth);
		const canvas = document.createElement('canvas');
		canvas.width = Math.round(video.videoWidth * scale);
		canvas.height = Math.round(video.videoHeight * scale);
		canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
		onPhoto(canvas.toDataURL('image/jpeg', 0.85));
	}

	show('off');
	return () => {
		stopCamera();
		wrap.remove();
	};
}

// Using it, on a fake agent.

// A fake agent to build with: it answers the photos it gets.
const lens = {
	name: 'Lens',
	onMessage: (message) => (message.image ? 'Thanks: I got your photo.' : 'Send me a photo.'),
};

// While building: the fake agent (every browser feature counts as allowed). In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { agent: lens } });

const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', maxWidth: '360px' });
const title = document.createElement('h2');
title.style.margin = '0';
const answer = document.createElement('p');
answer.style.margin = '0';
const place = document.createElement('div');
page.append(title, answer, place);
document.body.append(page);

camera(place, world, { onPhoto: (image) => world.send({ image, text: 'A photo' }) });
world.subscribe((node) => {
	const last = node.messages.filter((message) => !message.fromMe).at(-1);
	title.textContent = node.name;
	answer.textContent = last ? last.text : 'Take a photo and Lens will get it.';
});
Live, on a fake world
Open

When the camera does not start (no camera on the device, a refusal, a camera busy in another app) the component replaces the video with a text that names the reason. Every failure except a refusal in the webapp also gets a Try again button.

How it asks for the camera ​

The camera is one of the features that need the consent of the person first in the webapp and then in the browser. The component asks for both only when the person presses the button:

  1. The webapp. If world.webapp.allowed does not include 'camera', the component calls world.askFor(['camera']) and the webapp shows a dialog that names your site. After a yes the webapp reloads your view with the camera allowed and the next press skips this step. A no makes askFor reject with 'declined'. Because every new askFor for the camera rejects at once until the webapp reloads your view, the component reports the refusal without a retry button.
  2. The browser. navigator.mediaDevices.getUserMedia then shows the permission prompt of the browser. The prompt names the UNaIVERSE site and not yours. Its Promise rejects with one of three errors: (1) NotAllowedError when the browser refuses, (2) NotFoundError or OverconstrainedError when no camera matches and (3) NotReadableError when another app holds the camera.

During development only the browser asks for the camera because a fake world counts every feature as allowed and resolves askFor at once (The camera and the rest of the browser).

Take a photo draws the current frame onto a canvas at most 640 pixels wide and passes onPhoto a JPEG data URI (quality 0.85) that world.send({ image, text }) accepts as it is. The front camera is shown mirrored and the photo is not. The camera stops on Turn off and when the component unmounts.

Props ​

PropDefaultWhat it is
world(required)The world or agent returned by useWorld.
onPhotononeA (image) => void callback called with each photo as a JPEG data URI. Without it there is no Take a photo button.
facing'user''user' for the front camera (shown mirrored) or 'environment' for the back one.

Parameters ​

camera(container, world, options) renders the video box and its buttons into container.

ParameterWhat it is
containerThe element to render into.
worldThe world or agent that connectToHost resolves with.
options.onPhotoA (image) => void callback called with each photo as a JPEG data URI.
options.facing'user' (default) or 'environment'.

It returns a function that stops the camera and removes the rendered elements.

Change it ​

  • Send frames without a button by calling takePhoto on a timer while the camera is on. Each frame is a separate message and a few per second are the most a timer should send.
  • Add the microphone. Ask for ['camera', 'microphone'] and pass audio: true to getUserMedia.
  • Make the photos smaller with a width below 640 or a JPEG quality below 0.85 to send fewer bytes in each message.
  • Know in advance whether the webapp will ask. world.webapp.allowed.includes('camera') is false until the person lets your view use the camera.

See also ​

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