# 이미지 width, height 값 가져오기

이미지 본래의 사이즈를 가져와야 할 때 어떻게 하면 되는지 알아보겠습니다.

  • onLoad 메소드는 이미지가 로드 되면 실행되는 함수로 이미지에 대한 정보를 넘겨줍니다.
  • 우리는 image 엘리먼트를 잡아서 naturalHeight, naturalWidth로 이미지 본래의 크기를 알아냅니다.
const checkImageWithHeight = ({ target: img }) => {
    // target은 콘솔로 찍어보면 <img alt="preview" onLoad={checkImageWithHeight} src={...}  /> 아렇게 이미지 엘리먼트가 들어갑니다.
    console.log(img.naturalHeight, img.naturalWidth);
};

<img alt="preview" onLoad={checkImageWithHeight} src={...}  />
#JS
노경환
이 글이 도움이 되셨다면! 깃헙 스타 부탁드립니다 😊😄
최근변경일: 3/25/2024, 12:16:11 PM