개요

프로젝트에서 클릭한 위치에 이미지를 배치하고, 새로고침을 해도 이미지가 고정되어야 하는 페이지가 있었다.

그런데 문제는 웹앱이다보니 기기가 달라지면 그 위치가 달라지는 문제가 있었다.

 

해결법

1. 현재 창의 X,Y 좌표를 구한다.

getBoundingClientRect().x 

getBoundingClientRect().y

 

2. 브라우저에서 사용자에게 웹페이지가 보여지는 영역의 x,y 좌표를 구한다.

clientX

clientY

 

3. 2번에서 1번을 뺀 값을 이미지가 들어갈 컴포넌트의 높이, 너비로 나누어주고, 100을 곱한다.

매번 컴포넌트 높이, 너비가 달라지기 때문에 비율을 구한 것이다.

 

✳️컴포넌트의 높이, 너비 구하는 법

 <Bottoms ref={componentRef}>

 

컴포넌트 속성에 ref = {componentRef}를 해주고, 아래 코드를 넣어주면 된다!

const componentRef = useRef(null);

  useEffect(() => {
    if (componentRef.current) {
      const w = componentRef.current.offsetWidth;
      const h = componentRef.current.offsetHeight;
      console.log("Width:", w);
      console.log("Height:", h);
      setComponentWidth(w);
      setComponentHeight(h);
    }
  }, []);

 

4. 3번까지 해주고, 이미지를 position : absolute로, 해당 컴포넌트를 position : relative로 해준다.

이미지 top, left를 각각 ⬇️이렇게 설정해주면 된다.

  top: `${(imagePosition.YPer * componentHeight) / 100}px`,
  left: `${(imagePosition.XPer * componentWidth) / 100}px`,

 

728x90
cowboysj