Created
October 30, 2024 15:12
-
-
Save JonathanLoscalzo/46bcb35ef1193a3ca7b214c3517e4848 to your computer and use it in GitHub Desktop.
This file contains 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 './App.css'; | |
import React, { useState, useEffect } from 'react'; | |
// Implement an interface for drawing 2D bounding boxes on top of an image. | |
// Requirements: | |
// * The user should be able to click-and-drag on the image to draw a box. | |
// * Boxes should remain on the image after they are drawn. | |
// * Boxes should be able to overlap each other. | |
function ImgBoxAnnotator({img}) { | |
const [rectangles, setRectangles] = useState([]) | |
const [mouseDown, setMouseDown] = useState(false) | |
const [position, setPosition] = useState({ | |
initial: {x:null, y:null}, | |
end:{x:null, y:null} | |
}) | |
const onMouseDown = (event)=>{ | |
setMouseDown(true) | |
setPosition({ | |
initial: { | |
x:event.nativeEvent.offsetX, | |
y:event.nativeEvent.offsetY | |
}, | |
end:{ | |
x:event.nativeEvent.offsetX, | |
y:event.nativeEvent.offsetY | |
} | |
}) | |
console.log(position) | |
} | |
const onMouseUp = ()=> { | |
setMouseDown(false) | |
const rectangle = drawRect() | |
console.log(rectangle) | |
setRectangles([...rectangles, rectangle]) | |
setPosition({ | |
initial: {x:null, y:null}, | |
end:{x:null, y:null} | |
}) | |
} | |
const drawRect = () => { | |
const width = Math.abs(position.initial.x - position.end.x) | |
const height = Math.abs(position.initial.y - position.end.y) | |
const x = Math.min(position.initial.x, position.end.x) | |
const y = Math.min(position.initial.y, position.end.y) | |
return <rect | |
key={rectangles.length} | |
className={'rectangle'} | |
x={x} | |
y={y} | |
width={width} | |
height={height} | |
/> | |
} | |
const onMouseMove = (event)=> { | |
setPosition({ | |
...position, | |
end:{ | |
x:event.nativeEvent.offsetX, | |
y:event.nativeEvent.offsetY | |
} | |
}) | |
} | |
return <> | |
<svg | |
width={'300px'} | |
height={'200px'} | |
src={img} | |
onMouseDown={onMouseDown} | |
onMouseUp={onMouseUp} | |
onMouseMove={onMouseMove}> | |
<image | |
width={'300px'} | |
height={'200px'} | |
href={img} /> | |
{rectangles} | |
</svg> | |
</> | |
} | |
const App = () => { | |
const [count, setCount] = useState(0); | |
return ( | |
<div className="App"> | |
<ImgBoxAnnotator | |
img={"https://i.imgur.com/3fwi40p.jpg"}/> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment