Skip to content

Annotator Instance

The Annotator instance provides programmatic control over annotations.

Use the useAnnotator hook to access the annotator instance:

import { useAnnotator } from "annota";
function MyComponent() {
const annotator = useAnnotator();
// annotator may be null initially
if (!annotator) return null;
// Use annotator...
}

Add a single annotation:

annotator.addAnnotation({
id: "ann-1",
shape: {
type: "point",
geometry: { x: 100, y: 200 },
},
properties: {
label: "Cell",
},
style: {
fill: "#FF0000",
},
});

Add multiple annotations at once:

annotator.addAnnotations([
{ id: "ann-1", shape: { type: "point", geometry: { x: 100, y: 100 } } },
{ id: "ann-2", shape: { type: "point", geometry: { x: 200, y: 200 } } },
]);

Update an existing annotation:

annotator.updateAnnotation("ann-1", {
properties: { label: "Updated" },
style: { fill: "#00FF00" },
});

Delete an annotation by ID:

annotator.deleteAnnotation("ann-1");

Get a single annotation by ID:

const annotation = annotator.getAnnotation("ann-1");

Get all annotations:

const all = annotator.getAnnotations();

Set selected annotation IDs:

annotator.setSelected(["ann-1", "ann-2"]);

Clear all selections:

annotator.clearSelection();

Get selected annotations:

const selected = annotator.getSelected();

Undo the last action:

annotator.undo();

Redo the last undone action:

annotator.redo();

Check if undo/redo is available:

if (annotator.canUndo()) {
annotator.undo();
}

Listen to events:

annotator.on("createAnnotation", (annotation) => {
console.log("Created:", annotation);
});

Remove event listener:

const handler = (annotation) => console.log(annotation);
annotator.on("createAnnotation", handler);
// Later...
annotator.off("createAnnotation", handler);

Emit a custom event:

annotator.emit("customEvent", { data: "value" });

Merge selected annotations into one:

const merged = annotator.mergeSelected();

Zoom to fit an annotation in view:

annotator.fitToAnnotation("ann-1", { padding: 0.1 });
import { useAnnotator } from "annota";
import { useEffect } from "react";
function AnnotationManager() {
const annotator = useAnnotator();
useEffect(() => {
if (!annotator) return;
// Load annotations from API
fetch("/api/annotations")
.then((res) => res.json())
.then((annotations) => {
annotator.addAnnotations(annotations);
});
// Listen for changes
const handleChange = (annotation) => {
fetch(`/api/annotations/${annotation.id}`, {
method: "PATCH",
body: JSON.stringify(annotation),
});
};
annotator.on("updateAnnotation", handleChange);
return () => {
annotator.off("updateAnnotation", handleChange);
};
}, [annotator]);
return null;
}