Help with animation as you scroll with javascript

4

I have a vector image

<img src="images/first-page/vectors/waves-723178.svg" alt="Imagem vetorial decorativa" class="vector-wave">

and it is positioned to the left of the screen

.vector-wave {
    position: relative;
    transform: translate(-500px, 420px);
    z-index: 0;
}

showing only part of the image.

The question is: when I "scroll" my page, this image should go right to some extent;

In order to "scrollo" down the image goes to the right, if it does not, "scrollo" up the image to return left.

Example: Notice the image to the left of this url

PS: I saw a plug in called Super scroll orama, but I found it complicated to use, if someone knows how to use it, it would help me a lot too.

    
asked by anonymous 11.06.2015 / 05:35

1 answer

2

You need to know 3 things:

  • scroll height
  • screen width
  • the specific scroll at all times

Knowing the height of the scroll and the width of the screen you know the proportion that the image should move for each size of scroll. To know the dimensions you can use .getBoundingClientRect()

To know the scroll you currently have to add an event dropper to scroll .

A simple example would look like this:

var dimensoes = document.body.getBoundingClientRect();
var altura = dimensoes.height;
var largura = dimensoes.width;
var imagem = document.querySelector('img');

window.addEventListener('scroll', function () {
    var scroll = window.scrollY;
    var posImagem = scroll * largura / altura;
    imagem.style.left = posImagem + 'px';
});

jsFiddle: link

    
11.06.2015 / 08:30