Skip to content

Camera ​

Un agente che legge un documento, un gioco a gesti e una cabina per fototessere hanno tutti bisogno di un'immagine di quello che la persona mostra. Camera disegna un pulsante Turn on the camera che accende la fotocamera della persona e ne mostra il video dal vivo. Con una callback onPhoto aggiunge un pulsante Take a photo che cattura il fotogramma corrente e lo passa a onPhoto. La tua callback può poi inviare la foto al mondo o all'agente.

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

Quando la fotocamera non parte (il dispositivo non ne ha una, la persona rifiuta, un'altra app la sta usando) il componente sostituisce il video con un testo che ne dice il motivo. Ogni errore tranne un rifiuto nella webapp ha anche un pulsante Try again.

Come chiede la fotocamera ​

La fotocamera è una delle funzioni che richiedono il consenso della persona e il consenso va dato prima nella webapp e poi nel browser. Il componente chiede tutti e due i consensi solo quando la persona preme il pulsante:

  1. La webapp. Se world.webapp.allowed non contiene 'camera', il componente chiama world.askFor(['camera']) e la webapp mostra una finestra di dialogo che nomina il tuo sito. Dopo un sì la webapp ricarica la tua vista con la fotocamera permessa e la pressione successiva salta questo passo. Un no fa rifiutare askFor con 'declined'. Visto che fino al ricaricamento della tua vista ogni nuovo askFor per la fotocamera viene rifiutato subito, il componente segnala il rifiuto senza un pulsante per riprovare.
  2. Il browser. Poi navigator.mediaDevices.getUserMedia mostra la richiesta di permesso del browser. La richiesta nomina il sito di UNaIVERSE e non il tuo. La sua Promise viene rifiutata con uno di tre errori: (1) NotAllowedError quando il browser rifiuta, (2) NotFoundError o OverconstrainedError quando nessuna fotocamera corrisponde e (3) NotReadableError quando un'altra app tiene occupata la fotocamera.

Durante lo sviluppo la fotocamera la chiede solo il browser perché un mondo finto considera permessa ogni funzione e risolve subito askFor (La fotocamera e il resto del browser).

Take a photo disegna il fotogramma corrente su un canvas largo al massimo 640 pixel e passa a onPhoto un data URI JPEG (qualità 0.85) che world.send({ image, text }) accetta così com'è. La fotocamera frontale è mostrata a specchio mentre la foto non lo è. La fotocamera si ferma con Turn off e quando il componente viene smontato.

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo o l'agente restituito da useWorld.
onPhotonessunoUna callback (image) => void chiamata con ogni foto come data URI JPEG. Senza la callback non c'è il pulsante Take a photo.
facing'user''user' per la fotocamera frontale (mostrata a specchio) o 'environment' per quella posteriore.

Parametri ​

camera(container, world, options) disegna dentro container il riquadro del video e i suoi pulsanti.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo o l'agente con cui si risolve connectToHost.
options.onPhotoUna callback (image) => void chiamata con ogni foto come data URI JPEG.
options.facing'user' (predefinito) o 'environment'.

Restituisce una funzione che ferma la fotocamera e rimuove gli elementi disegnati.

Modificalo ​

  • Invia fotogrammi senza pulsante chiamando takePhoto con un timer mentre la fotocamera è accesa. Ogni fotogramma è un messaggio a sé e un timer non dovrebbe inviarne più di qualcuno al secondo.
  • Aggiungi il microfono. Chiedi ['camera', 'microphone'] e passa audio: true a getUserMedia.
  • Rendi le foto più piccole con una larghezza sotto i 640 pixel o una qualità JPEG sotto 0.85 per inviare meno byte in ogni messaggio.
  • Sappi in anticipo se la webapp chiederà. world.webapp.allowed.includes('camera') è false finché la persona non permette alla tua vista di usare la fotocamera.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.