PhotoSwipeでギャラリーを作る方法

PhotoSwipeでギャラリーを作る方法

今回はワタシの大好きな写真プラグイン「PhotoSwipe」です。このサイト自体にすでに導入済みなので、サンプルは「デモページ」でご確認ください。

また、以前にWordPressでPhotoSwipeを導入する方法として『WordPressで簡単にPhotoSwipeを利用する方法』という記事も書いてあるので、ご参考くださればと思います。

なお、最新のPhotoSwipe v5については以下の記事をご参考ください。

HTMLコード

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
   <title>PhotoSwipe demo</title>
   <!-- jQuery -->
   <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>

   <!-- Core CSS file -->
   <link rel="stylesheet" href="/assets/PhotoSwipe-master/dist/photoswipe.css"> 
   <!-- Skin CSS file (styling of UI - buttons, caption, etc.)
   In the folder of skin CSS file there are also:
   - .png and .svg icons sprite, 
   - preloader.gif (for browsers that do not support CSS animations) -->
   <link rel="stylesheet" href="/assets/PhotoSwipe-master/dist/default-skin/default-skin.css"> 
   <!-- Core JS file -->
   <script src="/assets/PhotoSwipe-master/dist/photoswipe.min.js"></script> 
   <!-- UI JS file -->
   <script src="/assets/PhotoSwipe-master/dist/photoswipe-ui-default.min.js"></script> 
</head>
<body>

   <!-- スライドショーのギャラリーの定義 -->
   <!-- Root element of PhotoSwipe. Must have class pswp. -->
   <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
      <!-- Background of PhotoSwipe. 
      It's a separate element as animating opacity is faster than rgba(). -->
      <div class="pswp__bg"></div>
      <!-- Slides wrapper with overflow:hidden. -->
      <div class="pswp__scroll-wrap">
         <!-- Container that holds slides. 
         PhotoSwipe keeps only 3 of them in the DOM to save memory.
         Don't modify these 3 pswp__item elements, data is added later on. -->
         <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
         </div>
         <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
         <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
               <!--  Controls are self-explanatory. Order can be changed. -->
               <div class="pswp__counter"></div>
               <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
               <button class="pswp__button pswp__button--share" title="Share"></button>
               <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
               <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
               <!-- Preloader demo https://codepen.io/dimsemenov/pen/yyBWoR -->
               <!-- element will get class pswp__preloader--active when preloader is running -->
               <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 class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
               <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
               <div class="pswp__caption__center"></div>
            </div>
         </div>
      </div>
   </div>

   <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">

      <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
         <a href="https://www.single-life.tokyo/wp-content/uploads/2021/07/DSC06344.jpg" itemprop="contentUrl" data-size="1200x800">
            <img src="https://www.single-life.tokyo/wp-content/uploads/2021/07/DSC06344.jpg" itemprop="thumbnail" title="レッサーパンダ" style="width:20%" />
         </a>
         <figcaption itemprop="caption description">レッサーパンダさん</figcaption>
      </figure>

      <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
         <a href="https://www.single-life.tokyo/wp-content/uploads/2021/07/DSC07591.jpg" itemprop="contentUrl" data-size="1200x800">
            <img src="https://www.single-life.tokyo/wp-content/uploads/2021/07/DSC07591.jpg" itemprop="thumbnail" alt="カピパラ" style="width:20%" />
         </a>
         <figcaption itemprop="caption description"  style="display:none" >カピパラさん</figcaption>
      </figure>
      <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
         <a href="https://www.single-life.tokyo/wp-content/uploads/2021/07/DSC07708.jpg" itemprop="contentUrl" data-size="1200x800">
            <img src="https://www.single-life.tokyo/wp-content/uploads/2021/07/DSC07708.jpg" itemprop="thumbnail" alt="ペンギン" style="width:20%" />
         </a>
         <figcaption itemprop="caption description"  style="display:none" >ペンギンさん</figcaption>
      </figure>
   </div>

   <!-- 別ファイルにしてあります-->
   <script type="text/javascript" src="myPhotoswipe.js"></script>

   <script>
      // execute above function
      initPhotoSwipeFromDOM('.my-gallery');
   </script>
</body>
</html>

JSファイルコード(myPhotoswipe.js)

/* 日本語を書いた場合はUTF-8で保存*/
var initPhotoSwipeFromDOM = function(gallerySelector) {
    // parse slide data (url, title, size ...) from DOM elements 
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
        var thumbElements = el.childNodes,
            numNodes = thumbElements.length,
            items = [],
            figureEl,
            linkEl,
            size,
            item;
        for(var i = 0; i < numNodes; i++) {
            figureEl = thumbElements[i]; // <figure> element
            // include only element nodes 
            if(figureEl.nodeType !== 1) {
                continue;
            }
            linkEl = figureEl.children[0]; // <a> element
            size = linkEl.getAttribute('data-size').split('x');
            // create slide object
            item = {
                src: linkEl.getAttribute('href'),
                w: parseInt(size[0], 10),
                h: parseInt(size[1], 10)
            };

            if(figureEl.children.length > 1) {
                // <figcaption> content
                item.title = figureEl.children[1].innerHTML; 
            }
            if(linkEl.children.length > 0) {
                // <img> thumbnail element, retrieving thumbnail url
                item.msrc = linkEl.children[0].getAttribute('src');
            } 
            item.el = figureEl; // save link to element for getThumbBoundsFn
            items.push(item);
        }

        return items;
    };

    // find nearest parent element
    var closest = function closest(el, fn) {
        return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };
    // triggers when user clicks on thumbnail
    var onThumbnailsClick = function(e) {
        e = e || window.event;
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        var eTarget = e.target || e.srcElement;

        // find root element of slide
        var clickedListItem = closest(eTarget, function(el) {
            return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
        });

        if(!clickedListItem) {
            return;
        }

        // find index of clicked item by looping through all child nodes
        // alternatively, you may define index via data- attribute
        var clickedGallery = clickedListItem.parentNode,
            childNodes = clickedListItem.parentNode.childNodes,
            numChildNodes = childNodes.length,
            nodeIndex = 0,
            index;

        for (var i = 0; i < numChildNodes; i++) {
            if(childNodes[i].nodeType !== 1) { 
                continue; 
            }

            if(childNodes[i] === clickedListItem) {
                index = nodeIndex;
                break;
            }
            nodeIndex++;
        }
        if(index >= 0) {
            // open PhotoSwipe if valid index found
            openPhotoSwipe( index, clickedGallery );
        }
        return false;
    };
    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
        var hash = window.location.hash.substring(1),
        params = {};

        if(hash.length < 5) {
            return params;
        }

        var vars = hash.split('&');
        for (var i = 0; i < vars.length; i++) {
            if(!vars[i]) {
                continue;
            }
            var pair = vars[i].split('=');  
            if(pair.length < 2) {
                continue;
            }           
            params[pair[0]] = pair[1];
        }
        if(params.gid) {
            params.gid = parseInt(params.gid, 10);
        }
        return params;
    };
    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
        var pswpElement = document.querySelectorAll('.pswp')[0],
            gallery,
            options,
            items;
        items = parseThumbnailElements(galleryElement);
        // define options (if needed)
        options = {
            // define gallery index (for URL)
            galleryUID: galleryElement.getAttribute('data-pswp-uid'),
            getThumbBoundsFn: function(index) {
                // See Options -> getThumbBoundsFn section of documentation for more info
                var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                    pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                    rect = thumbnail.getBoundingClientRect(); 
                return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
            }
            /* 日本語にカスタマイズ */
            ,shareButtons: [
                {id:'facebook', label:'Facebookで共有', url:'https://www.facebook.com/sharer/sharer.php?u={{url}}'},
                {id:'twitter', label:'ツイート', url:'https://twitter.com/intent/tweet?text={{text}}&url={{url}}'},
            /*  {id:'pinterest', label:'Pin it', url:'http://www.pinterest.com/pin/create/button/?url={{url}}&media={{image_url}}&description={{text}}'},*/ /* Pinterestは利用しない */
                {id:'download', label:'ダウンロード', url:'{{raw_image_url}}', download:true}
            ],
        };
        // PhotoSwipe opened from URL
        if(fromURL) {
            if(options.galleryPIDs) {
                // parse real index when custom PIDs are used 
                // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
                for(var j = 0; j < items.length; j++) {
                    if(items[j].pid == index) {
                        options.index = j;
                        break;
                    }
                }
            } else {
                // in URL indexes start from 1
                options.index = parseInt(index, 10) - 1;
            }
        } else {
            options.index = parseInt(index, 10);
        }
        // exit if index not found
        if( isNaN(options.index) ) {
            return;
        }
        if(disableAnimation) {
            options.showAnimationDuration = 0;
        }
        // Pass data to PhotoSwipe and initialize it
        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    };
    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );
    for(var i = 0, l = galleryElements.length; i < l; i++) {
        galleryElements[i].setAttribute('data-pswp-uid', i+1);
        galleryElements[i].onclick = onThumbnailsClick;
    }
    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
        openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
};

デモ

PhotoSwipeの導入方法

PhotoSwipeのサイトは以下にあります。

2021年11月6日現在の最新バージョンは「4.1.3」のようですね。ただ、すでにVersion.5もベータ版ですができているみたいです。ただ、今回は最新版の「4.1.3」前提で説明しています。

ダウンロード

まず、最初、プログラインのソース一式、ZIPの書庫ファイルをダウンロードしてきます。

まず、書庫ファイルをダウンロードして下さい。

ダウンロードしたZIPファイルを展開してください。展開すると以下のようなフォルダ内容が展開されます。

これを、今回のサンプルでは「(ウェブルート)/assets/」に展開しました。

コーディング方法

次にコーディング方法を説明していきます。

手順は、以下のページに書かれていますので、それに沿って行きます。

JS/CSSファイルインクルード

ダウンロードした書庫ファイルの中に「dist」というフォルダがあり、その中に必要なJS/CSSファイルが含まれています。

   <!-- jQuery -->
   <script src="https://code.jquery.com/jquery-3.6.0.js" ></script>

   <!-- Core CSS file -->
   <link rel="stylesheet" href="/assets/PhotoSwipe-master/dist/photoswipe.css"> 
   <!-- Skin CSS file (styling of UI - buttons, caption, etc.)
   In the folder of skin CSS file there are also:
   - .png and .svg icons sprite, 
   - preloader.gif (for browsers that do not support CSS animations) -->
   <link rel="stylesheet" href="/assets/PhotoSwipe-master/dist/default-skin/default-skin.css"> 
   <!-- Core JS file -->
   <script src="/assets/PhotoSwipe-master/dist/photoswipe.min.js"></script> 
   <!-- UI JS file -->
   <script src="/assets/PhotoSwipe-master/dist/photoswipe-ui-default.min.js"></script> 

PhotoSwipeのJSファイルとCSSファイルをインクロードしつつ、その前に、jQueryも読み込んでおきましょう。

PhotoSwipeエレメント追加

次にHTMLのbodyタグ内に、全画面表示時の定義のHTMLを書き込みます。

ここでは直にHTMLを書き込んでいますがJSファイルで動的にHTMLコードを埋め込んでもよいでしょう。

   <!-- スライドショーのギャラリーの定義 -->
   <!-- Root element of PhotoSwipe. Must have class pswp. -->
   <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
      <!-- Background of PhotoSwipe. 
      It's a separate element as animating opacity is faster than rgba(). -->
      <div class="pswp__bg"></div>
      <!-- Slides wrapper with overflow:hidden. -->
      <div class="pswp__scroll-wrap">
         <!-- Container that holds slides. 
         PhotoSwipe keeps only 3 of them in the DOM to save memory.
         Don't modify these 3 pswp__item elements, data is added later on. -->
         <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
         </div>
         <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
         <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
               <!--  Controls are self-explanatory. Order can be changed. -->
               <div class="pswp__counter"></div>
               <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
               <button class="pswp__button pswp__button--share" title="Share"></button>
               <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
               <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
               <!-- Preloader demo https://codepen.io/dimsemenov/pen/yyBWoR -->
               <!-- element will get class pswp__preloader--active when preloader is running -->
               <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 class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
               <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
               <div class="pswp__caption__center"></div>
            </div>
         </div>
      </div>
   </div>

このHTMLの定義には、全画面表示時の前ボタン、次ボタン、閉じるボタン、共有ボタン、フルスクリーンボタン、ズームボタンなどの定義があります。

写真/ギャラリー定義追加

次に実際に表示したい写真を追加します。

構文は、以下の通りです。

   <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
      <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
         <a href="(写真1URI)" itemprop="contentUrl" data-size="(全画面表示時の横サイズ)x(全画面表示時の縦サイズ)">
            <img src="(写真1URI)" itemprop="thumbnail"  />
         </a>
         <figcaption itemprop="caption description">(写真1のキャプション)</figcaption>
      </figure>
      <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
         <a href="(写真2URI)" itemprop="contentUrl" data-size="(全画面表示時の横サイズ)x(全画面表示時の縦サイズ)">
            <img src="(写真2URI)" itemprop="thumbnail"  />
         </a>
         <figcaption itemprop="caption description">(写真2のキャプション)</figcaption>
      </figure>
      ...
   </div>

figureタグの内部にaタグを設定し、さらにその中に写真イメージのimgタグを設定します

キャプションを追加する場合にはfigcaptionを設定します。

初期化(PhotoSwipeコンストラクタ実行)

最後に、jQueryでPhotoSwipeのコンストラクタを実行します。

        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();

コンストラクタの引数は4つになります。

第1引数全画面表示のエレメント
(「 PhotoSwipeエレメント追加 」で追加したエレメント)
第2引数PhotoSwipe UIのクラスを指定してください。
ただ、「photoswipe-ui-default.js」を読み込んでいる場合には『PhotoSwipeUI_Default』を指定してください。
第3引数写真項目の配列オブジェクト
第4引数オプション。
オプションについてはここにレファレンスがあります。

以上のようにコンストラクタを呼び出せばよいのですが、やや難しいため、「Getting Started」に記載されているソースをコピーし、ワタシはそれを『myPhotoswipe.js』というJSファイルにしました。

ただし、一部、日本語にしています。ソーシャル連携について、文字列が英語だったので日本語にカスタマイズしましたね。

ご参考いただければと思います。

非常にクールな写真表示方法になるのではないでしょうか。

ぜひ、ご利用を検討してみてください。

ご参考

関連ページ