Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Parallax with basicScroll + angular2
- ////////////////////////// html
- <div id="parallax-container" *ngIf="!parallaxDisabled">
- <img class="parallax-layer"
- [src]="'/assets/img/parallax/' + i + '.' + (webpEnabled? 'webp' : 'png')"
- [src]="'/assets/img/parallax/' + i + '.png')"
- [attr.name]="image.name? image.name : null"
- [attr.data-speed]="image.speed? image.speed : 0"
- *ngFor="let image of parallaxImages; let i = index">
- </div>
- ////////////////////////// component
- parallaxDisabled: boolean = true;
- parallaxWidth: number = 750;
- parallaxImages: any[] = [
- {speed: 86, name: 'gradient-clouds'},
- {speed: 63, name: 'castle'},
- {speed: 40, name: 'grass'},
- {speed: 30, name: 'glass'}
- ];
- animating: boolean = false;
- ngAfterViewInit() {
- // TODO MAYBE DISABLE THIS ON SAFARI
- document.querySelectorAll('.parallax-layer').forEach((elem) => {
- const modifier: number = parseInt(elem.getAttribute('data-speed'));
- basicScroll.create({
- elem: elem,
- from: '0',
- to: '1000px',
- direct: true,
- props: {
- '--translateY': {
- from: '0',
- to: `${ 10 * modifier }px`
- }
- }
- }).start();
- });
- }
- ngOnInit() {
- window.addEventListener('resize', this.resize, true); // third parameter
- if (window.innerWidth >= this.parallaxWidth) {
- this.parallaxDisabled = false;
- }
- }
- resize = (): void => {
- this.parallaxDisabled = window.innerWidth < this.parallaxWidth ? true : false;
- }
- scroll = (): void => {
- this.animate();
- }
- animate() {
- window.requestAnimationFrame(() => {
- if (this.animating || this.parallaxDisabled) {
- return;
- }
- this.animating = true;
- const parent = document.getElementById('parallax-container');
- if (!parent) {
- return;
- }
- // let parallaxOffset = window.pageYOffset;
- // let parallaxOffset = document.body.scrollTop);
- const parallaxOffset = window.scrollY;
- // Only do the parallax transform if the parent is on the view
- if (parallaxOffset < parent.clientHeight) {
- const children = parent.getElementsByTagName('div');
- for (let i = 0; i < children.length; i++) {
- // Using translate3d for maximum performance
- const speed = parseInt(children[i].getAttribute('data-speed'));
- const yPos = (parallaxOffset * speed / 100).toFixed(0);
- children[i].style.transform = 'translate3d(0px, ' + yPos + 'px, 0px)';
- /*
- let yPos = -(parallaxOffset * i / children.length);
- children[i].style.transform = 'translate3d(0px, ' + yPos + 'px, 0px)';
- parent.style.transform = 'translate3d(0px, ' + -yPos + 'px, 0px)';
- */
- }
- }
- setTimeout(() => {
- this.animating = false;
- });
- });
- }
Add Comment
Please, Sign In to add comment