Invia una foto dalla fotocamera
Per inviare quello che vede la fotocamera, copia su un canvas il fotogramma attuale del video, codifica il canvas come data URI e passalo a world.send({ image, text }). Il mondo riceve l'immagine e il suo testo come un messaggio della persona. Se hai una fotocamera premi Start the camera e poi Send a photo. Quando non c'è nessuna fotocamera o il browser la blocca, l'esempio lo segnala.
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>
</>
);
}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 : '';
});Come funziona
- La fotocamera va in un
<video>da cuidrawImage(video, ...)copia sul canvas il fotogramma attuale. canvas.toDataURL('image/jpeg', 0.8)codifica il canvas in un data URI JPEG da passare asendcomeimage. Per tenere piccolo il messaggio l'esempio limita il canvas a 640 pixel di larghezza.sendsi risolve con'sent','failed'(retryinvia di nuovo il messaggio) o'not-allowed'(il mondo adesso non accetta un messaggio).
La fotocamera richiede il sì della persona sia nella webapp sia nel browser. Dopo il sì nella webapp la tua vista si carica di nuovo e la ricetta Chiedi la fotocamera solo quando serve fa partire la fotocamera subito dopo quel ricaricamento. Dove non c'è nessuna fotocamera, <input type="file" accept="image/*"> permette alla persona di scegliere una foto senza nessuna richiesta di permesso.