2016-04-23 9 views
0

Photoswipeを使用してギャラリーにロードしたい画像の配列がありますが、画像の幅と高さを事前に定義する際に問題があります。Prewload Photoswipe Galleryの画像

var sizeOf = require('image-size'); 
 
    var url = require('url'); 
 
    var http = require('http'); 
 

 
    var slideshow = []; 
 

 
    for(var i = 0; i < listing.listing_images.length; i++) { 
 
     var image = listing.listing_images[i]; 
 
     var width, height = 0; 
 
     var imgUrl = image.url; 
 
     var options = url.parse(imgUrl); 
 

 
     http.get(options, function (response) { 
 
      var chunks = []; 
 
      response.on('data', function (chunk) { 
 
       chunks.push(chunk); 
 
      }).on('end', function() { 
 
       var buffer = Buffer.concat(chunks); 
 
       **height = sizeOf(buffer).height; 
 
       width = sizeOf(buffer).width;** 
 
      }); 
 
     }); 
 
     var item = { 
 
      src: image.url, 
 
      h: height, 
 
      w: width 
 
     }; 
 

 

 
     slideshow.push(item); 
 
    } 
 

 

 
    res.render('example.ejs', { 
 
     listing: listing, 
 
     slides: slideshow 
 
    });
:具体的には、私はここに、ここで私はEJSページが使用するローカル変数としてスライドやリストを定義しています、ページをレンダリングするために私のJSだ画像に

をプリロードする必要があると思います

<% var slides = locals.slides %> 
 
<script> 
 
$('document').ready(function() { 
 
    var pswpElement = document.querySelectorAll('.pswp')[0]; 
 

 
    // build items array using slideshow variable 
 
    var items = <%- JSON.stringify(slides) %>; 
 
    console.log(items); 
 

 
    // grab image 
 

 
    if (items.length > 0) { 
 
     // define options (if needed) 
 
     var options = { 
 
      // optionName: 'option value' 
 
      // for example: 
 
      index: 0 // start at first slide 
 
     }; 
 

 
     // Initializes and opens PhotoSwipe 
 
     var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options); 
 
     gallery.init(); 
 

 
    } 
 

 
</script>

そして、ここではEJSページ内のスクリプトです

基本的には、photoswipeアイテムの配列は問題ありませんが、photoswipeが初期化して読み込むまで幅と高さは設定されません。したがって、画像の高さと幅がまだ設定されていないため、画像が表示されません。

Photoswipeに渡す前に幅が&の高さになるように、スライドショーアレイの画像の読み込みをトリガーする方法はありますか?また、最初に0に設定してから、後で高さと幅を更新して、photoswipeに強制的にリロードさせようとしましたが、photoswipeはイメージの新しい高さ/幅を認識しませんでした。

申し訳ありませんこれのいずれかがejsナンセンスで不明瞭/混乱している場合は、何かお気軽にお問い合わせください。私は明確にしたいと思います。

おかげAPIを活用し、これを解決することになった

答えて

0

gallery.listen('gettingData', function(index, item) { 
     // index - index of a slide that was loaded 
     // item - slide object 
     var img = new Image(); 
     img.src = item.src; 
     item.h = img.height; 
     item.w = img.width; 
    }); 

    gallery.invalidateCurrItems(); 
// updates the content of slides 
    gallery.updateSize(true); 

誰もがこれを読んだことが起こり、そこに新しいIMGを作成せずに画像サイズを読み込むための良い方法はありますか、この私を最適化した場合あなたの提案が大好きです。 :)

関連する問題