Skip to main content

A toolbar and labels that follow items

Add HTML labels and a compact toolbar to a modular sofa builder. Each label follows its module as the customer orbits, pans, or zooms. The toolbar selects a module in Mimeeq and shows its measured size beside the overall scene dimensions.

Use window.mimeeqApp.actions.getInstanceScreenRect(instanceId) to project a placed item, window.mimeeqApp.observers.modular.sceneItems to identify items, and the window.mimeeqApp.observers.scene and window.mimeeqApp.observers.camera groups to know when to redraw.

Complete example​

Replace YOUR_MODULAR_SHORT_CODE with the short code for an inline modular embed with a starter layout, and YOUR_CANVAS_TEMPLATE with a template that fills the embed with the canvas. Hide the header and option panel in that template. The overlay shares the canvas origin and size in this layout. Orbit, pan or zoom, then select an item using its overlay button.

<style>
#label-stage {
position: relative;
overflow: hidden;
}
#label-stage mmq-embed {
display: block;
width: 100%;
}
#item-labels {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 2;
}
#item-labels button {
position: absolute;
transform: translate(-50%, -100%);
pointer-events: auto;
background: white;
color: #202020;
border: 1px solid #555;
border-radius: 4px;
padding: 4px 8px;
}
</style>

<div id="label-stage">
<mmq-embed
short-code="YOUR_MODULAR_SHORT_CODE"
template="YOUR_CANVAS_TEMPLATE"
locale="en"
render-at-mount></mmq-embed>
<div id="item-labels" aria-label="Placed items" hidden></div>
</div>
<p id="item-measurements" aria-live="polite">Waiting for the 3D scene…</p>

<script>
document.addEventListener(
'mimeeq-app-loaded',
() => {
const { actions, observers } = window.mimeeqApp;
const { camera, modular, scene, status } = observers;
const stage = document.getElementById('label-stage');
const layer = document.getElementById('item-labels');
const dimensions = document.getElementById('item-measurements');
if (!stage || !layer || !dimensions) return;

/** @type {Map<string, HTMLButtonElement>} */
const buttons = new Map();
let frame = 0;
let stopped = false;

function canDraw() {
return Boolean(status.firstRender.getValue() && status.settled.getValue());
}

/** @param {ReturnType<typeof scene.bounds.getValue>} bounds */
function size(bounds) {
return bounds
? [bounds.width, bounds.height, bounds.depth].map((n) => n.toFixed(2)).join(' × ') + ' m'
: 'unavailable';
}

const draw = async () => {
if (!canDraw() || stopped) return;
const items = Object.values(modular.sceneItems.getValue() ?? {});
const projections = await Promise.all(
items.map(({ instanceId }) => actions.getInstanceScreenRect(instanceId)),
);
if (!canDraw() || stopped || !stage.isConnected) return;

const liveItems = modular.sceneItems.getValue() ?? {};
const itemBounds = scene.instanceBounds.getValue() ?? {};
layer.hidden = false;
const visibleIds = new Set();

items.forEach(({ instanceId }, index) => {
const item = liveItems[instanceId];
const rect = projections[index];
if (!item || !rect) return;

const x = rect.x + rect.width / 2;
const y = rect.y;
if (x < 0 || x > layer.clientWidth || y < 0 || y > layer.clientHeight) return;

visibleIds.add(instanceId);
let button = buttons.get(instanceId);
if (!button) {
button = document.createElement('button');
button.type = 'button';
button.addEventListener('click', async () => {
if (!canDraw() || !modular.sceneItems.getValue()?.[instanceId]) return;
try {
await actions.selectElement(instanceId);
} catch (error) {
console.error('Could not select the item.', error);
}
});
buttons.set(instanceId, button);
layer.append(button);
}
button.textContent = `Select ${item.productName} · ${size(itemBounds[instanceId])}`;
button.style.left = `${x}px`;
button.style.top = `${y}px`;
});

for (const [id, button] of buttons) {
button.hidden = !visibleIds.has(id);
if (!liveItems[id]) {
button.remove();
buttons.delete(id);
}
}
};

let drawing = false;
let pending = false;
const scheduleDraw = () => {
dimensions.textContent = `Scene W × H × D: ${size(scene.bounds.getValue())}`;
if (!canDraw()) layer.hidden = true;
pending = true;
if (stopped || drawing || frame) return;

frame = requestAnimationFrame(async () => {
frame = 0;
pending = false;
drawing = true;
try {
await draw();
} catch (error) {
layer.hidden = true;
console.error('Could not project the item labels.', error);
} finally {
drawing = false;
if (pending) scheduleDraw();
}
});
};

const subscriptions = [
...[status.firstRender, status.settled].map((observer) => observer.subscribe(scheduleDraw)),
scene.bounds.subscribe(scheduleDraw),
scene.instanceBounds.subscribe(scheduleDraw),
modular.sceneItems.subscribe(scheduleDraw),
camera.position.subscribe(scheduleDraw),
camera.target.subscribe(scheduleDraw),
camera.zoomLevel.subscribe(scheduleDraw),
camera.projectionMode.subscribe(scheduleDraw),
camera.isAnimating.subscribe(scheduleDraw),
];
const resize = new ResizeObserver(scheduleDraw);
resize.observe(stage);
window.addEventListener(
'pagehide',
() => {
stopped = true;
cancelAnimationFrame(frame);
resize.disconnect();
subscriptions.forEach((subscription) => subscription.unsubscribe());
},
{ once: true },
);
},
{ once: true },
);
</script>
<script src="https://cdn.mimeeq.com/read_models/embed/app-embed.js" async></script>

How it works​

  1. Register the mimeeq-app-loaded listener on document before loading the embed script. Wait for status.firstRender and status.settled before projecting items.
  2. Read placed items and use their instance IDs as label keys. Two modules can share a product ID while needing separate labels. Read scene.instanceBounds by the same keys and use scene.bounds for the overall readout.
  3. Subscribe to pose, zoom, projection, and animation changes. status.settled reflects canvas blockers, object dragging, and pending 3D tasks. Redraw on camera updates, and hide the overlay while the scene is loading, processing tasks, or dragging an object.
  4. Project each item and anchor the button to the top center of its rectangle. The overlay fills the same area as the canvas, so the canvas-relative offsets can be used directly. Leave the overlay transparent to pointer input except at the buttons.
  5. Coalesce updates with requestAnimationFrame and reuse the buttons so a camera update preserves keyboard focus. Unsubscribe and disconnect the resize observer when removing this UI.

Observer payloads​

Subscriptions emit { newValue, oldValue } and replay the current value immediately. The initial emission can omit oldValue. Use getValue() to read synchronously. Treat returned values as read-only snapshots, including copied camera points.

Observer fieldTypeMeaning and empty state
modular.sceneItemsRecord<string, ModularSceneItem>Map keyed by instanceId. Empty when no items are placed. Each item has string fields instanceId, productId, productCode, productName, and configurationCode, plus a numeric positionOrder starting at 1 along world X.
status.firstRenderbooleanThe mounted scene has drawn its first frame.
status.settledbooleanThe main product is loaded, the canvas is unblocked, no drag is active, and no 3D tasks are pending.
status.busybooleanAt least one 3D task is unfinished.
scene.boundsSceneBounds | nullOverall measured geometry. null means there is no measured geometry.
scene.instanceBoundsRecord<string, SceneBounds>Measured item bounds keyed by instance ID. Starts empty. A missing key means there are no measured bounds for that item.
camera.position, camera.target{ x: number; y: number; z: number } | nullEye and look-at point in Y-up scene coordinates. null means there is no interactive camera.
camera.zoomLevelnumber | nullEye-to-target distance in perspective or half the visible height in orthographic projection. null means there is no interactive camera.
camera.projectionMode'perspective' | 'orthographic' | nullCurrent projection. null means there is no interactive camera.
camera.isAnimatingboolean | nullA finite camera transition is running. Idle rotation and gesture inertia can still move the pose while this is false. null means there is no interactive camera.
SceneBounds fieldTypeMeaning
width, height, depthnumberWorld-axis-aligned span along X, Y, and Z in metres.
min, max{ x: number; y: number; z: number }World-space corners in metres.

getInstanceScreenRect() resolves to { x, y, width, height } in CSS pixels or null. x and y are offsets from the canvas's top-left corner. A rectangle can extend outside the canvas. null covers missing geometry, a missing camera or canvas, and bounds intersecting or behind the camera.

Edge cases​

  • The overlay subscribes to camera pose and zoom changes. It follows the main camera on drawn frames and keeps its last position during screenshot capture.
  • Bounds update after an item drag ends. A rotated item can have different world-axis-aligned dimensions. For measurements in millimetres, multiply the bounds by 1,000.
  • Two items can overlap in screen space. The example anchors each independently. The rectangle describes projection, so an item can be occluded even when it has a rectangle.
  • The canvas and overlay must share the same origin and dimensions. If your page places controls alongside the canvas, size and position the overlay to match the canvas area in your layout.

See Simpler ways to do common tasks, Scene and catalog, Camera controls, and the Observers guide.