Last active
April 25, 2021 11:30
-
-
Save rsimon/2391fdf2c49bdeef5125407306c2db93 to your computer and use it in GitHub Desktop.
Minimal example for using https://annotorious.com in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef, useState } from 'react'; | |
import { Annotorious } from '@recogito/annotorious'; | |
import '@recogito/annotorious/dist/annotorious.min.css'; | |
function App() { | |
// Ref to the image DOM element | |
const imgEl = useRef(); | |
// The current Annotorious instance | |
const [ anno, setAnno ] = useState(); | |
// Current drawing tool name | |
const [ tool, setTool ] = useState('rect'); | |
// Init Annotorious when the component | |
// mounts, and keep the current 'anno' | |
// instance in the application state | |
useEffect(() => { | |
let annotorious = null; | |
if (imgEl.current) { | |
// Init | |
annotorious = new Annotorious({ | |
image: imgEl.current | |
}); | |
// Attach event handlders here | |
annotorious.on('createAnnotation', annotation => { | |
console.log('created', annotation); | |
}); | |
annotorious.on('updateAnnotation', (annotation, previous) => { | |
console.log('updated', annotation, previous); | |
}); | |
annotorious.on('deleteAnnotation', annotation => { | |
console.log('deleted', annotation); | |
}); | |
} | |
// Keep current Annotorious instance in state | |
setAnno(annotorious); | |
// Cleanup: destroy current instance | |
return () => annotorious.destroy(); | |
}, []); | |
// Toggles current tool + button label | |
const toggleTool = () => { | |
if (tool === 'rect') { | |
setTool('polygon'); | |
anno.setDrawingTool('polygon'); | |
} else { | |
setTool('rect'); | |
anno.setDrawingTool('rect'); | |
} | |
} | |
return ( | |
<div> | |
<div> | |
<button | |
onClick={toggleTool}> | |
{ tool === 'rect' ? 'RECTANGLE' : 'POLYGON' } | |
</button> | |
</div> | |
<img | |
ref={imgEl} | |
src="640px-Hallstatt.jpg" | |
alt="Hallstatt Town Square" /> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment