[javascript] PhotoSwipe를 이용한 이미지 화면 에디터 구현 방법

PhotoSwipe는 Javascript 기반의 이미지 및 동영상 뷰어 라이브러리로, 모바일 및 데스크톱에서 사용할 수 있습니다. 이 라이브러리를 활용하여 이미지 화면 에디터를 구현하는 방법에 대해 알아보겠습니다.

1. PhotoSwipe 라이브러리 사용 준비

PhotoSwipe를 사용하기 위해 라이브러리를 다운로드하거나 CDN을 통해 가져옵니다. 아래는 CDN을 이용한 방법입니다.

<!-- CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/default-skin/default-skin.min.css" />

<!-- JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>

2. HTML 구조 설정

이미지 화면 에디터를 구성하기 위해 다음과 같은 HTML 구조를 설정합니다.

<div class="gallery">
  <div class="gallery-items">
    <figure class="gallery-item">
      <a href="path/to/image1.jpg" data-size="800x600">
        <img src="path/to/image1.jpg" alt="Image 1">
      </a>
    </figure>
    <figure class="gallery-item">
      <a href="path/to/image2.jpg" data-size="800x600">
        <img src="path/to/image2.jpg" alt="Image 2">
      </a>
    </figure>
    <!-- 추가 이미지들 -->
  </div>
</div>

3. Javascript 코드 작성

이미지 화면 에디터를 초기화하기 위해 Javascript 코드를 작성합니다.

// PhotoSwipe 초기화
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [];

var galleryItems = document.querySelectorAll('.gallery-item');
galleryItems.forEach(function(item) {
  var anchor = item.querySelector('a');
  var size = anchor.getAttribute('data-size').split('x');
  
  var itemData = {
    src: anchor.getAttribute('href'),
    w: parseInt(size[0]),
    h: parseInt(size[1])
  };
  
  items.push(itemData);
  
  anchor.addEventListener('click', function(e) {
    e.preventDefault();
    
    var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {index: index});
    gallery.init();
  });
});

4. CSS 스타일링

PhotoSwipe를 적용하기 위한 CSS 스타일링을 추가합니다.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-gap: 10px;
}

.gallery-item {
  position: relative;
  cursor: pointer;
}

.gallery-item img {
  width: 100%;
  height: auto;
}

5. 실행 확인

위의 코드를 적용하여 이미지 화면 에디터를 실행해보세요. 각 이미지를 클릭하면 PhotoSwipe를 통해 이미지가 크게 확대되어 보여질 것입니다.

PhotoSwipe를 이용하여 이미지 화면 에디터를 구현하는 방법에 대해 알아보았습니다. PhotoSwipe의 다양한 옵션과 기능을 사용하여 사용자 친화적인 에디터를 구현할 수 있습니다.

참조: