I am currently working on capturing the coordinates of an image in order to add tags to it. While I can successfully add a tag, the issue arises when I resize the browser - the tag does not adjust to the corresponding position of the image. As the browser expands or scales down, the image maintains its aspect ratio, but the tag remains static relative to the current viewport position and not the actual location of the image. Although, if I scroll, the tag does eventually move to its correct area, but only after scrolling takes place.
const initialPosition = {
x: "",
y: "",
};
const MediaPage = ({ user, mediaId }) => {
const [tagPosition, setTagPosition] = useState(initialPosition);
const imageWrapRef = createRef();
const handleTagClick = (e) => {
const { left, top } = imageWrapRef.current.getBoundingClientRect();
const x = e.pageX - left;
const y = e.pageY - top;
setTagPosition((prev) => ({ ...prev, x, y }));
};
return (
<div
onClick={(e) => handleTagClick(e)}
ref={imageWrapRef}
>
<div
style={{
left: `${tagPosition.x}px`,
top: `${tagPosition.y}px`,
zIndex: 2,
padding: 10,
position: "absolute",
}}
>
1
</div>
<Image
onLoad={handleLoadingComplete}
className="w-full"
alt=""
src="URL"
layout="responsive"
width={700}
height={800}
/>
</div>
}
In essence, my goal is to enable users to click on an image and have a tag appear at the precise position of the image, regardless of any scaling that may occur.