DataImage
A world can keep a picture in its data (a map, a board, a chart drawn by an agent or a photo that changes). DataImage renders that picture in an <img> and replaces it each time the world gives a new one. Until the first picture arrives a placeholder of the same size holds its place and the layout does not shift.
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>
);
}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' });A picture in world.data is a data URI that goes directly into img.src. A real world gives its pictures as PNG or JPEG data URIs and the fake world of the example gives a new SVG data URI every second. The webapp sends a large picture to your view only when it changes (The data of the world). To keep the browser from decoding the same picture again, the component also assigns src only when the data URI differs from the current one.
alt is required and names what the picture shows ('The garden, with its house and the sun' in the example).
Props
| Prop | Default | What it is |
|---|---|---|
world | (required) | The world returned by useWorld. |
name | (required) | The name of the picture in world.data. |
alt | (required) | The text alternative of the picture. |
caption | none | A caption under the picture. |
height | 240 | The height of the picture box as a number of pixels or a CSS length. The picture keeps its aspect ratio inside the box. |
Parameters
dataImage(container, world, options) renders into container and updates the picture whenever it changes.
| Parameter | What it is |
|---|---|
container | The element to render into. |
world | The world that connectToHost resolves with. |
options.name | The name of the picture in world.data. |
options.alt | The text alternative of the picture. |
options.caption | A caption under the picture. |
options.height | The height of the picture box as a CSS length. Default '240px'. |
It returns a function that unsubscribes from the world and removes the picture.
Change it
- Fill the box and crop the edges by changing
objectFitfrom'contain'to'cover'. - Scale pixel art and small boards without blur with
imageRendering: 'pixelated'. - Show a camera stream of many pictures a second with
VideoFrame.VideoFramelistens withonDataonly to that key of the data instead of to every change of the world. - Let the person open the picture full screen with
FullScreenPicture.
See also
- Show a picture from data: the same idea in a few lines.
VideoFrame: a picture that changes many times a second.Grid: for a grid of values in place of a picture.