【问题标题】:Preload Images for Photoswipe Gallery为 Photoswipe 图库预加载图像
【发布时间】:2016-04-23 22:41:18
【问题描述】:

所以我有一组图像我想使用 Photoswipe 加载到画廊中,但是我无法预定义图像的宽度和高度。具体来说,我认为我需要预加载图像

这是我的 JS 来呈现页面,这里我将幻灯片和列表定义为 ejs 页面使用的局部变量:

    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 页面中的脚本:

<% 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>

基本上发生的事情是 photoswipe 项目的数组被很好地传递,但是直到 photoswipe 初始化并触发 img 加载时才设置宽度和高度。所以图像不显示,因为它们的高度和宽度尚未设置。

有没有办法触发幻灯片数组中图像的加载,以便在传递给 Photoswipe 之前设置宽度和高度?我还尝试查看是否可以将它们最初设置为 0,然后尝试稍后更新高度和宽度并尝试强制 photoswipe 重新加载,但 photoswipe 无法识别图像的新高度/宽度。

很抱歉,如果其中有任何不清楚/混淆了 ejs 废话,请随时提出任何问题,我很乐意澄清。

谢谢

【问题讨论】:

    标签: ejs photoswipe


    【解决方案1】:

    最终利用 API 解决了这个问题:

    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 或优化此内容,我会很乐意提出建议。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多