Rectangle Tool Demo

1. With toolbar and layer UI

Use the toolbar to activate the Rectangle tool; create and edit rectangles as usual.

How to use

  • Activate the Rectangle Tool from the toolbar.
  • Click and drag to create a rectangle; drag corners to resize, drag fill to move.

2. Headless: continual bounding boxes (no built-in UI)

This viewer intentionally has no toolbar and no layer UI, so you can see how to build your own user-friendly “bounding box” experience on top of the library. A common UX is continual box drawing: after the user completes one box, the next one is immediately ready so they can label many regions quickly.

Continual drawing off.
Count: 0

Code: headless rectangle tool + continual drawing

// Create toolkit without UI; add default and rectangle tools.
const tk = new AnnotationToolkit(viewer, { addUI: false });
tk.addTools(['default', 'rectangle']);

const rectangleTool = tk.getTool('rectangle');
const defaultTool = tk.getTool('default');

// Style for new rectangles.
const boxStyle = {
  strokeColor: 'blue',
  fillColor: 'red',
  fillOpacity: 0.2,
  rescale: { strokeWidth: 2 },
};

// When enabling continual drawing: activate rectangle tool with a new placeholder,
// and on each item-created, create the next placeholder so the tool re-enters create mode.
function onRectangleItemCreated(payload) {
  const createdStyle = payload?.item?.defaultStyle || payload?.item?.style;
  const styleOpts = createdStyle?.toJSON ? createdStyle.toJSON() : createdStyle;
  tk._ensureNewItemForTool(styleOpts || boxStyle);
}

rectangleTool.addEventListener('item-created', onRectangleItemCreated);
rectangleTool.activate({ createNewItem: true, style: boxStyle }); // no toolbar: must activate programmatically

// To turn off: remove listener and switch back to default tool.
rectangleTool.removeEventListener('item-created', onRectangleItemCreated);
defaultTool.activate();