Help with scroll animation with javascript

Asked

Viewed 95 times

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;
}

then display only part of the image.

The point is: when I "scroll" my page, this image should go right to a certain extent;

So that if "scroll" down the image goes to the right, if I contract, "scroll" up the image return to the left.

Example:Note the image that is to the left of this url

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

1 answer

2


You need to know three things:

  • scroll height
  • screen width
  • the specific scroll every moment

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

To know the scroll at the moment you need to add an event receiver to the scroll.

A simple example would be 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: http://jsfiddle.net/d2bu5edu/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.