Send a photo from the camera
To send what the camera sees, copy the current frame of the video onto a canvas, encode the canvas as a data URI and pass it to world.send({ image, text }). The world receives the picture and its text as a message of the person. If you have a camera, press Start the camera and then Send a photo. When there is no camera or the browser blocks it, the example says so.
jsx
import { useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world that answers each photo with its size.
const booth = {
name: 'Photo booth',
onMessage: (message) => (message.image ? `Nice photo! (${Math.round(message.image.length / 1024)} kB)` : 'Send me a photo.'),
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: booth } });
const [isOn, setIsOn] = useState(false);
const [note, setNote] = useState('The camera is off.');
const video = useRef(null);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
async function startCamera() {
try {
// First the yes in the webapp, for this view (see "Ask for the camera only when needed").
if (!world.webapp.allowed.includes('camera')) {
await world.askFor(['camera']); // after a yes, the webapp loads the view again
return;
}
video.current.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
setIsOn(true);
setNote('The camera is on.');
} catch (error) {
setNote(error.code === 'declined' ? 'You said no to the camera.' : `No camera could start here (${error.name}).`);
}
}
async function sendPhoto() {
// The picture of the video at this moment, on a canvas at most 640 pixels wide to keep the message small.
const { videoWidth, videoHeight } = video.current;
const scale = Math.min(1, 640 / videoWidth);
const canvas = document.createElement('canvas');
canvas.width = Math.round(videoWidth * scale);
canvas.height = Math.round(videoHeight * scale);
canvas.getContext('2d').drawImage(video.current, 0, 0, canvas.width, canvas.height);
// `send` takes the image as a data URI, here a JPEG.
const result = await world.send({ image: canvas.toDataURL('image/jpeg', 0.8), text: 'My photo' });
setNote(result === 'sent' ? 'Photo sent.' : `Not sent (${result}).`);
}
const last = world.messages.filter((message) => !message.fromMe).at(-1);
return (
<>
<video ref={video} hidden={!isOn} autoPlay muted playsInline style={{ width: 240 }} />
<button onClick={startCamera}>Start the camera</button>
<button onClick={sendPhoto} disabled={!isOn}>Send a photo</button>
<p>{note}</p>
<p>{last ? last.text : ''}</p>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that answers each photo with its size.
const booth = {
name: 'Photo booth',
onMessage: (message) => (message.image ? `Nice photo! (${Math.round(message.image.length / 1024)} kB)` : 'Send me a photo.'),
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: booth } });
const video = document.createElement('video');
video.hidden = true;
video.autoplay = true;
video.muted = true;
video.playsInline = true;
video.style.width = '240px';
const start = document.createElement('button');
start.textContent = 'Start the camera';
const snap = document.createElement('button');
snap.textContent = 'Send a photo';
snap.disabled = true;
const note = document.createElement('p');
note.textContent = 'The camera is off.';
const answer = document.createElement('p');
document.body.append(video, start, snap, note, answer);
start.onclick = async () => {
try {
// First the yes in the webapp, for this view (see "Ask for the camera only when needed").
if (!world.webapp.allowed.includes('camera')) {
await world.askFor(['camera']); // after a yes, the webapp loads the view again
return;
}
video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
video.hidden = false;
snap.disabled = false;
note.textContent = 'The camera is on.';
} catch (error) {
note.textContent = error.code === 'declined' ? 'You said no to the camera.' : `No camera could start here (${error.name}).`;
}
};
snap.onclick = async () => {
// The picture of the video at this moment, on a canvas at most 640 pixels wide to keep the message small.
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);
// `send` takes the image as a data URI, here a JPEG.
const result = await world.send({ image: canvas.toDataURL('image/jpeg', 0.8), text: 'My photo' });
note.textContent = result === 'sent' ? 'Photo sent.' : `Not sent (${result}).`;
};
// Called at once, then after every change of the world.
world.subscribe((node) => {
const last = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = last ? last.text : '';
});How it works
- The camera plays in a
<video>from whichdrawImage(video, ...)copies the current frame onto a canvas. canvas.toDataURL('image/jpeg', 0.8)encodes the canvas as a JPEG data URI thatsendtakes asimage. The example caps the canvas at 640 pixels of width to keep the message small.sendresolves with'sent','failed'(retrysends the message again) or'not-allowed'(the world does not accept a message now).
The camera needs a yes from the person both in the webapp and in the browser. Your view loads again after the yes in the webapp and the recipe Ask for the camera only when needed starts the camera at once after that reload. Where there is no camera at all, <input type="file" accept="image/*"> lets the person pick a photo without any permission prompt.