Skip to content

useTool

Activate and manage annotation tools for creating and editing annotations.

function useTool(options: UseToolOptions): void;
interface UseToolOptions {
viewer: OpenSeadragon.Viewer | null;
handler: Tool | null;
enabled?: boolean;
}
ParameterTypeDescription
viewerViewer | nullOpenSeadragon viewer instance
handlerTool | nullTool instance to activate
enabledbooleanWhether the tool is enabled (default: true)
import { useTool, PointTool } from "annota";
import { useState } from "react";
function AnnotationTools({ viewer }) {
const pointTool = new PointTool();
useTool({
viewer,
handler: pointTool,
enabled: true,
});
return null;
}
import { useTool, PointTool, RectangleTool, PolygonTool } from "annota";
import { useState, useMemo } from "react";
function ToolController({ viewer }) {
const [activeTool, setActiveTool] = useState<string>("pan");
// Create tools once
const tools = useMemo(() => ({
point: new PointTool(),
rectangle: new RectangleTool(),
polygon: new PolygonTool(),
}), []);
useTool({
viewer,
handler: activeTool === "pan" ? null : tools[activeTool],
enabled: activeTool !== "pan",
});
return (
<div>
<button
onClick={() => setActiveTool("pan")}
style={{ fontWeight: activeTool === "pan" ? "bold" : "normal" }}
>
Pan
</button>
<button
onClick={() => setActiveTool("point")}
style={{ fontWeight: activeTool === "point" ? "bold" : "normal" }}
>
Point
</button>
<button
onClick={() => setActiveTool("rectangle")}
style={{ fontWeight: activeTool === "rectangle" ? "bold" : "normal" }}
>
Rectangle
</button>
<button
onClick={() => setActiveTool("polygon")}
style={{ fontWeight: activeTool === "polygon" ? "bold" : "normal" }}
>
Polygon
</button>
</div>
);
}
function TumorTool({ viewer }) {
const tool = useMemo(
() =>
new PolygonTool({
style: {
fill: "#FF0000",
fillOpacity: 0.3,
stroke: "#FF0000",
strokeWidth: 2,
},
layer: "tumor",
properties: {
type: "tumor",
},
}),
[]
);
useTool({
viewer,
handler: tool,
enabled: true,
});
return null;
}
function ToolsWithShortcuts({ viewer }) {
const [activeTool, setActiveTool] = useState("pan");
const tools = useMemo(() => ({
point: new PointTool(),
rectangle: new RectangleTool(),
polygon: new PolygonTool(),
}), []);
// Keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.target instanceof HTMLInputElement) return;
switch (e.key.toLowerCase()) {
case "v": setActiveTool("pan"); break;
case "p": setActiveTool("point"); break;
case "r": setActiveTool("rectangle"); break;
case "g": setActiveTool("polygon"); break;
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, []);
useTool({
viewer,
handler: activeTool === "pan" ? null : tools[activeTool],
enabled: activeTool !== "pan",
});
return <div>Active: {activeTool} (Press V/P/R/G to switch)</div>;
}