[javascript] PhotoSwipe를 이용한 이미지 플리퍼 효과 구현 방법

먼저, PhotoSwipe 라이브러리를 다운로드하고 웹 페이지에 포함해야 합니다. 다운로드한 파일 중 photoswipe.css와 photoswipe.js 파일을 웹 페이지의 head 태그 안에 포함시킵니다.

<head>
  ...
  <link rel="stylesheet" href="photoswipe.css">
  <script src="photoswipe.js"></script>
  ...
</head>

그리고 이미지가 포함된 HTML 요소를 추가합니다. 예를 들어, 이미지가 들어있는 div 요소를 생성합니다. 그리고 각 이미지에 data-size 속성을 추가하여 이미지의 원본 크기를 지정합니다.

<div id="image-gallery">
  <figure>
    <a href="image1.jpg" data-size="800x600">
      <img src="thumbnail1.jpg" alt="Image 1">
    </a>
    <figcaption>Image 1</figcaption>
  </figure>
  <figure>
    <a href="image2.jpg" data-size="1024x768">
      <img src="thumbnail2.jpg" alt="Image 2">
    </a>
    <figcaption>Image 2</figcaption>
  </figure>
  ...
</div>

위의 예시에서는 이미지와 해당 이미지의 썸네일을 a 태그로 감싸고 있습니다. a 태그의 href 속성은 이미지의 원본 경로를 지정하며, data-size 속성은 원본 이미지의 크기를 지정합니다.

마지막으로, 아래의 JavaScript 코드를 추가하여 PhotoSwipe를 초기화합니다.


var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [];

// 이미지 갤러리에 속한 각 이미지의 정보를 배열에 추가
document.querySelectorAll('#image-gallery a').forEach(function(el) {
  var src = el.getAttribute('href');
  var size = el.getAttribute('data-size').split('x');
  var item = {
    src: src,
    w: parseInt(size[0], 10),
    h: parseInt(size[1], 10)
  };
  items.push(item);
});

// 이미지 클릭 시 PhotoSwipe 열기
document.querySelectorAll('#image-gallery a').forEach(function(el, index) {
  el.addEventListener('click', function(e) {
    e.preventDefault();
    var options = {
      index: index,
      shareButtons: [{
        id: 'download',
        label: 'Download Image',
        url: '{{raw_image_url}}',
        download: true
      }]
    };
    var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
  });
});

위의 코드에서 첫 번째 줄은 pswpElement 변수를 생성합니다. 이 변수는 PhotoSwipe의 DOM 요소(HTML 구조)를 참조할 것입니다. 그리고 items 배열을 생성하여 이미지 갤러리에 있는 각 이미지의 정보를 저장합니다.

그리고 이미지를 클릭할 때 PhotoSwipe를 열기 위해 click 이벤트를 등록합니다. 각 이미지를 클릭하면 해당 이미지의 인덱스와 설정 옵션을 사용하여 PhotoSwipe 인스턴스를 생성하고 초기화합니다.

이제 웹 페이지에서 이미지를 클릭하면 PhotoSwipe 갤러리가 열리고 이미지를 플리퍼 효과로 탐색할 수 있게 됩니다. 추가로, options 객체를 사용하여 해당 이미지에 대한 추가적인 설정을 수행할 수 있습니다.

더 많은 PhotoSwipe 옵션 및 사용법에 대해서는 공식 문서를 참조하시기 바랍니다.