[javascript] PhotoSwipe를 이용한 이미지 슬라이드쇼 구현 방법

이미지 슬라이드쇼는 웹사이트에서 사용자에게 이미지를 시각적으로 보여주는 효과적인 방법입니다. PhotoSwipe는 자바스크립트 라이브러리로, 터치 및 제스처를 지원하는 반응형 이미지 갤러리를 구현할 수 있게 해줍니다. 이번 포스트에서는 PhotoSwipe를 통해 이미지 슬라이드쇼를 구현하는 방법에 대해 알아보겠습니다.

PhotoSwipe 설치하기

PhotoSwipe를 사용하기 위해서는 먼저 해당 라이브러리를 다운로드하고 프로젝트에 포함시켜야 합니다. 다음은 npm을 사용하는 경우 PhotoSwipe를 설치하는 방법입니다:

npm install photoswipe

간단한 이미지 슬라이드쇼 구현하기

다음은 단순한 이미지 슬라이드쇼를 구현하는 예제입니다. 이 예제에서는 HTML, CSS, 그리고 자바스크립트를 사용하여 슬라이드쇼를 만들 것입니다.

  1. HTML 파일에 다음과 같이 슬라이드쇼를 표시할 컨테이너와 이미지 요소를 추가합니다:
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="pswp__bg"></div>
  <div class="pswp__scroll-wrap">
    <div class="pswp__container">
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
    </div>
    <div class="pswp__ui pswp__ui--hidden">
      <div class="pswp__top-bar">
        <div class="pswp__counter"></div>
        <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
      </div>
      <div class="pswp__preloader">
        <div class="pswp__preloader__icn">
          <div class="pswp__preloader__cut">
            <div class="pswp__preloader__donut"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="gallery">
  <figure>
    <img src="image1.jpg" alt="Image 1">
    <figcaption>Caption 1</figcaption>
  </figure>
  <figure>
    <img src="image2.jpg" alt="Image 2">
    <figcaption>Caption 2</figcaption>
  </figure>
  <figure>
    <img src="image3.jpg" alt="Image 3">
    <figcaption>Caption 3</figcaption>
  </figure>
</div>
  1. CSS 파일에 다음과 같이 슬라이드쇼에 적용될 스타일을 추가합니다:
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
}

.gallery figure {
  position: relative;
  overflow: hidden;
}

.gallery img {
  width: 100%;
  height: auto;
  display: block;
}

.gallery figcaption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  text-align: center;
}
  1. 자바스크립트 파일에 다음과 같이 슬라이드쇼를 초기화하는 코드를 작성합니다:
// PhotoSwipe 초기화
var pswpElement = document.querySelectorAll('.pswp')[0];
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, document.querySelectorAll('.gallery figure'), {
  index: 0
});

// 슬라이드쇼 실행 이벤트 처리
document.querySelectorAll('.gallery figure').forEach(function (figure, index) {
  figure.addEventListener('click', function () {
    gallery.options.index = index;
    gallery.init();
  });
});

이제 웹 브라우저에서 해당 HTML 파일을 열면 이미지 슬라이드쇼가 작동될 것입니다. 사용자가 이미지를 클릭하면 전체 화면 슬라이드쇼가 시작되며, 다양한 제스처를 사용하여 다음이미지로 넘어갈 수 있습니다.

PhotoSwipe를 사용하면 웹사이트에서 멋진 이미지 슬라이드쇼를 손쉽게 구현할 수 있습니다. 자세한 사용법은 PhotoSwipe 공식 문서를 참고하시기 바랍니다.

참고 자료: