Skip to content

DataImage ​

Un mondo può tenere un'immagine nei suoi dati (una mappa, una scacchiera, un grafico disegnato da un agente o una foto che cambia). DataImage mostra quell'immagine in un <img> e la sostituisce ogni volta che il mondo ne dà una nuova. Finché non arriva la prima immagine un segnaposto della stessa dimensione ne tiene il posto e il layout non si sposta.

jsx
import { useWorld } from './useWorld.js';

// The component: copy this part.

/**
 * DataImage: a picture that the world shows in its data, drawn again each time
 * the world gives a new one. Until the first picture arrives, a placeholder of
 * the same size keeps the page from jumping.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {string} props.name - The name of the picture in `world.data`.
 * @param {string} props.alt - What the picture shows, for those who cannot see it.
 * @param {string} [props.caption] - Words under the picture.
 * @param {number|string} [props.height=240] - The height of the picture, inside which it keeps its proportions.
 */
export function DataImage({ world, name, alt, caption, height = 240 }) {
	// A picture in `data` is an image source (a data URI), ready for an <img>.
	const source = world.data[name];
	const hasPicture = typeof source === 'string' && source.length > 0;
	const box = { width: '100%', height, borderRadius: 14, background: 'rgba(127, 127, 127, 0.12)' };

	return (
		<figure style={{ margin: 0, display: 'grid', gap: 6 }}>
			{hasPicture
				? <img src={source} alt={alt} style={{ ...box, display: 'block', objectFit: 'contain' }} />
				: <div role="img" aria-label={`${alt}: not here yet`} style={{ ...box, display: 'grid', placeItems: 'center', opacity: 0.6 }}>No picture yet</div>}
			{caption && <figcaption style={{ fontSize: 13, opacity: 0.75 }}>{caption}</figcaption>}
		</figure>
	);
}

// Using it, on a fake world.

/**
 * Draws the garden at a moment, as an SVG image source. The colour of the sky
 * and the place of the sun change with the time.
 * @param {number} time - The time (Unix ms).
 * @returns {string} The image source.
 */
function gardenAt(time) {
	const step = Math.floor(time / 1000) % 12;
	const sky = `hsl(${200 + step * 5} 70% ${80 - step * 3}%)`;
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
		<rect width="320" height="180" fill="${sky}"/>
		<circle cx="${30 + step * 24}" cy="${60 - Math.sin(step / 3.8) * 30}" r="18" fill="#F0A54E"/>
		<rect y="130" width="320" height="50" fill="#399D57"/>
		<rect x="140" y="95" width="40" height="35" fill="#9F466B"/></svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake world to build with: a new picture of the garden every second.
const garden = {
	name: 'Garden',
	data: { photo: { every: 1000, value: gardenAt } },
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<div style={{ maxWidth: 420 }}>
			<DataImage world={world} name="photo" alt="The garden, with its house and the sun" caption="The garden, live" />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/**
 * Draws into `container` a picture that the world shows in its data, and draws
 * it again each time the world gives a new one. Until the first picture arrives,
 * a placeholder of the same size keeps the page from jumping.
 * @param {HTMLElement} container - Where to draw it.
 * @param {object} world - The world, from connectToHost.
 * @param {{name: string, alt: string, caption?: string, height?: string}} options - The name of the
 *   picture in `world.data`, what it shows (for those who cannot see it), words under it, and its height.
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function dataImage(container, world, { name, alt, caption, height = '240px' }) {
	const box = { width: '100%', height, borderRadius: '14px', background: 'rgba(127, 127, 127, 0.12)' };
	const figure = document.createElement('figure');
	Object.assign(figure.style, { margin: '0', display: 'grid', gap: '6px' });
	const picture = document.createElement('img');
	picture.alt = alt;
	Object.assign(picture.style, box, { display: 'block', objectFit: 'contain' });
	const placeholder = document.createElement('div');
	placeholder.setAttribute('role', 'img');
	placeholder.setAttribute('aria-label', `${alt}: not here yet`);
	placeholder.textContent = 'No picture yet';
	Object.assign(placeholder.style, box, { display: 'grid', placeItems: 'center', opacity: '0.6' });
	figure.append(picture, placeholder);
	if (caption) {
		const words = document.createElement('figcaption');
		words.textContent = caption;
		Object.assign(words.style, { fontSize: '13px', opacity: '0.75' });
		figure.append(words);
	}
	container.append(figure);

	// Called at once, then after every change of the world.
	const stop = world.subscribe((node) => {
		// A picture in `data` is an image source (a data URI), ready for an <img>.
		const source = node.data[name];
		const hasPicture = typeof source === 'string' && source.length > 0;
		// Only a new picture goes to the <img>, to keep the browser from decoding the same one again.
		if (hasPicture && picture.getAttribute('src') !== source) picture.src = source;
		picture.style.display = hasPicture ? 'block' : 'none';
		placeholder.style.display = hasPicture ? 'none' : 'grid';
	});

	return () => {
		stop();
		figure.remove();
	};
}

// Using it, on a fake world.

/**
 * Draws the garden at a moment, as an SVG image source. The colour of the sky
 * and the place of the sun change with the time.
 * @param {number} time - The time (Unix ms).
 * @returns {string} The image source.
 */
function gardenAt(time) {
	const step = Math.floor(time / 1000) % 12;
	const sky = `hsl(${200 + step * 5} 70% ${80 - step * 3}%)`;
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
		<rect width="320" height="180" fill="${sky}"/>
		<circle cx="${30 + step * 24}" cy="${60 - Math.sin(step / 3.8) * 30}" r="18" fill="#F0A54E"/>
		<rect y="130" width="320" height="50" fill="#399D57"/>
		<rect x="140" y="95" width="40" height="35" fill="#9F466B"/></svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake world to build with: a new picture of the garden every second.
const garden = {
	name: 'Garden',
	data: { photo: { every: 1000, value: gardenAt } },
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: garden } });
const place = document.createElement('div');
place.style.maxWidth = '420px';
document.body.append(place);
dataImage(place, world, { name: 'photo', alt: 'The garden, with its house and the sun', caption: 'The garden, live' });
Live, on a fake world
Open

Un'immagine in world.data è un data URI che va direttamente in img.src. Un mondo vero dà le sue immagini come data URI PNG o JPEG e il mondo finto dell'esempio dà un nuovo data URI SVG ogni secondo. La webapp invia un'immagine grande alla tua vista solo quando cambia (I dati del mondo). Per evitare che il browser decodifichi di nuovo la stessa immagine, anche il componente assegna src solo quando il data URI è diverso da quello attuale.

alt è obbligatorio e dice che cosa mostra l'immagine ('The garden, with its house and the sun' nell'esempio).

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo restituito da useWorld.
name(obbligatorio)Il nome dell'immagine in world.data.
alt(obbligatorio)Il testo alternativo dell'immagine.
captionnessunoUna didascalia sotto l'immagine.
height240L'altezza del riquadro dell'immagine come numero di pixel o lunghezza CSS. Dentro il riquadro l'immagine conserva le sue proporzioni.

Parametri ​

dataImage(container, world, options) disegna dentro container e aggiorna l'immagine ogni volta che cambia.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo con cui si risolve connectToHost.
options.nameIl nome dell'immagine in world.data.
options.altIl testo alternativo dell'immagine.
options.captionUna didascalia sotto l'immagine.
options.heightL'altezza del riquadro dell'immagine come lunghezza CSS. Predefinito '240px'.

Restituisce una funzione che annulla l'iscrizione al mondo e rimuove l'immagine.

Modificalo ​

  • Riempi il riquadro tagliando i bordi cambiando objectFit da 'contain' a 'cover'.
  • Ingrandisci pixel art e scacchiere piccole senza sfocatura con imageRendering: 'pixelated'.
  • Mostra il flusso di una fotocamera con molte immagini al secondo con VideoFrame. VideoFrame ascolta con onData solo quella chiave dei dati invece di ogni cambiamento del mondo.
  • Lascia che la persona apra l'immagine a schermo intero con FullScreenPicture.

Vedi anche ​

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