Issue
I'm trying to get the coordinates of the image so I can add tags to it. I'm able to add the tag, but when I expand the browser, the tag doesn't follow to the correct position of the image. When browser gets expanded, or scaled down, the image scales correctly with the aspect ratio, however, the tag stays in the current place of the browser (not at the correct place of the image). However, if I scroll, it does move to the correct area, but that's only if scrolling occurs.
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>
}
So essentially, I'm trying to click on an image, and then a tag will appear. However, I need to be able to set the tag on the correct position of the image, even if it scales.
Solution
Found a solution, and it was an easy fix. Had to set parent div to relative position, and then update x and y for %
const x = ((e.clientX - left) / width) * 100;
const y = ((e.clientY - top) / height) * 100;
Then in the styling:
left: `${tagPosition.x}%`,
top: `${tagPosition.y}%`,
Answered By - hellomello
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.