多层视差,数学问题

时间:2018-03-05 21:15:54

标签: javascript parallax

我有一个目前半工作的多层视差脚本。如果让我们说具有视差效果的元素放在网站的顶部,那么效果就会发挥作用,因为当它滚出视图时你无法看到图层移出框架。

但是我希望能够在整个页面的多个元素上,在不同的位置使用此脚本。请参阅下面的示例,您可以看到效果正常,但如果您在data-parallax="panel-1"部分添加一些边距,您会看到现在存在问题。



/**
 * @author Martyn Lee Ball
 * @desc Creates multi-layer Parallax effect
 * @version 1.0
 * @return {Array} Returns instances of classes as Array
 */
class Parallax {

    constructor(node) {
        const self = this;

        // Settings and defaults
        self.settings = {
            container: node,
            height: node.clientHeight,
            name: node.dataset.parallax,
            layers: [],
            defaultDepth: 0.5,
            offset: function(element) {
                let top = 0;
                do {
                    top += element.offsetTop  || 0;
                    element = element.offsetParent;
                } while(element);

                return {
                    top: self.normalizeInt(top)
                };
            }.call(self, node)
        };

        // Populate layers setting with objects
        (function() {
            let layers = (self.settings.container).querySelectorAll('[data-layer]');
            let count = 0;
            for (const layer in layers) {
                if (layers.hasOwnProperty(layer)) {
                    self.settings.layers.push({

                        // Set the depth to the default if not defined
                        depth: (function() {
                            if (layers[layer].dataset.depth !== undefined)
                                return parseFloat(layers[layer].dataset.depth);
                            return self.settings.defaultDepth;
                        }.call(self)),

                        // Keep reference to the element
                        element: layers[layer],

                        // Get the layer name, not essential
                        name: layers[layer].dataset[layer]
                    });

                    // Fix layer heights
                    
                }
                count++;
            }
        }.call(this));

        this.setupScrollEvent.call(this);
    }

    normalizeInt(num) {
        return Math.round(num * 10) / 10;
    }

    setupScrollEvent() {
        const self = this;

        window.addEventListener('scroll', function() {
            self.last_known_scroll_position = window.scrollY || document.documentElement.scrollTop;
            if (!self.ticking) {
                window.requestAnimationFrame(function() {
                    self.scrolledEvent.call(self, self.last_known_scroll_position);
                    self.ticking = false;
                });
                self.ticking = true;
            }
        });
        self.last_known_scroll_position = window.scrollY || document.documentElement.scrollTop;
        self.scrolledEvent.call(self, self.last_known_scroll_position);
    }

    scrolledEvent(scrollY) {
        const self = this;

        if ((window.outerHeight + scrollY) < self.settings.offset.top) return;

        for (const layer in self.settings.layers) {
            if ((self.settings.layers).hasOwnProperty(layer)) {

                let movement = -self.normalizeInt((((scrollY * self.settings.layers[layer].depth) - scrollY)));
                let translate3d = 'translate3d(0, ' + movement + 'px, 0)';

                self.settings.layers[layer].element.style['-webkit-transform'] = translate3d;
                self.settings.layers[layer].element.style['-moz-transform'] = translate3d;
                self.settings.layers[layer].element.style['-ms-transform'] = translate3d;
                self.settings.layers[layer].element.style['-o-transform'] = translate3d;
                self.settings.layers[layer].element.style.transform = translate3d;
            }
        }
    }

    static initialize() {

        // Ensure DOM has loaded
        window.addEventListener('load', function() {

            let instances = [];

            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        instances.push(new this(panels[panel]));
                    }
                }
            }

            if (panels.length > 0) {
                window.parallaxInstance = instances;
            }
        }.bind(this));

    }
}
Parallax.initialize();
&#13;
html,
body {
  margin: 0;
  padding: 0;
}
section[data-parallax] {
  height: 400px;
  position: relative;
  overflow: hidden;
  border: 1px solid black;
  border-width: 1px 0 1px 0;
}
section[data-parallax] > div {
  position: absolute;
  z-index: -1;
  background-position: bottom center;
  background-size: auto;
  background-repeat: no-repeat;
  width: 100%;
  height: 100%;
}
section[data-parallax] > div[data-layer='layer-bg'] {
  background-image: url('https://i.imgur.com/F7pqpWZ.jpg');
}
section[data-parallax] > div[data-layer='layer-1'] {
  background-image: url('https://i.imgur.com/uxpVhe1.png');
  background-position: left bottom;
}
section[data-parallax] > div[data-layer='layer-2'] {
  background-image: url('https://i.imgur.com/JeGChIm.png');
}
section[data-parallax] > div[data-layer='layer-3'] {
  background-image: url('https://i.imgur.com/V7l8cxD.png');
  background-position: right bottom;
}
section[data-parallax] > div[data-layer='layer-4'] {
  background-image: url('https://i.imgur.com/joB5tI4.png');
}
section[data-parallax] > div[data-layer='layer-overlay'] {
  background-image: url('https://i.imgur.com/h1ybMNZ.png');
}
&#13;
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Parallax Development</title>
        <script src="parallax-dev.js" type="text/javascript"></script>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <section data-parallax="panel-1">
            <div data-layer="layer-bg" data-depth="0.10"></div>
            <div data-layer="layer-1" data-depth="0.20"></div>
            <div data-layer="layer-2" data-depth="0.50"></div>
            <div data-layer="layer-3" data-depth="0.80"></div>
            <div data-layer="layer-4" data-depth="1.0"></div>
        </section>
        <section style="padding-bottom: 200vh;"></section>
    </body>
</html>
&#13;
&#13;
&#13;

主要是我的问题是当我尝试从页面顶部移动视差元素时,因为现在可以看到移动较慢的图层的顶部。

我相信我需要做的是根据它们的深度调整这些图层的大小,例如深度值为0.10的图层非常慢。

所以我需要让图层显示如右下图所示,因为它们目前位于左侧? enter image description here

我一直在回到这一点,并试图让它在现在,开启和关闭几周。我真的不能理解我需要做的事情来解决这个问题,我相信它可以用一些简单的数学来训练层需要多大的数据,以便现在以用户身份显示边缘滚动。

1 个答案:

答案 0 :(得分:1)

即使我不确定我是否已经得到了这个问题,我也会尽力回答。

关于深度:您的代码已具有深度功能,因此您只需从数据深度attr读取深度,如下所示:

  defaultDepth: node.dataset.depth

并且您的照片具有相同的高度,因此对于这些特定的照片,您不必像右侧照片那样在顶部应用任何填充顶部或其他偏移。除非你有其他图片,否则应用深度就足够了。

这里有深度应用后我所拥有的: http://plnkr.co/edit/bNPzXFg83UtGF9PFWCQc?p=preview