requestAnimationFrame Parallax

by Denis Antonenko

HTML

<div class="bannerWrapper">
    <div class="banner">
        <div class="img item1"></div>
        <div class="img item2"></div>
        <div class="img item3"></div>
        <div class="img item4"></div>
        <div class="img item5"></div>
    </div>
</div>

CSS

* {
    margin: 0;
    padding: 0;
}
body {
}
.bannerWrapper {
    width: 100%;
    height: 300px;
    background-color: #9CCF14;
}
.banner {
    text-align: center;
    position: relative;
    background-image: url('http://c2n.me/3lJ1DCI.png');
    margin: auto;
    width: 1659px;
    height: 300px;
    overflow: hidden;
}
.img {
    position: absolute;
    display: none;
}
.item1 {
    background-image: url('http://c2n.me/3lJ0myG.png');
    left: 150px;
    top: 70px;
    width: 250px;
    height: 263px;
    background-repeat: no-repeat;
}
.item2 {
    background-image: url('http://c2n.me/3lIZYco.png');
    left: 340px;
    top:-20px;
    width: 300px;
    height: 199px;
    background-repeat: no-repeat;
}
.item3 {
    background-image: url('http://c2n.me/3lJ092T.png');
    width: 280px;
    height: 273px;
    left: 505px;
    top: -15px;
    background-repeat: no-repeat;
}
.item4 {
    background-image: url('http://c2n.me/3lJ0dY0.png');
    width: 238px;
    height: 154px;
    left: 812px;
    top: 150px;
    z-index: 1;
    background-repeat: no-repeat;
}
.item5 {
    background-image: url('http://c2n.me/3lJ0iaW.png');
    width: 416px;
    height: 512px;
    left: 1090px;
    top: -50px;
    z-index: 0;
    background-repeat: no-repeat;
}

JavaScript

var banner = $(".banner");
var imgs = $(".img");
var position = {
    x: 0,
    y: 0
};

banner.on('mousemove', function (event) {
    position.x = event.pageX;
    position.y = event.pageY;
});

function showAllObjects(object) {
    object.fadeIn(900);
}

function moving(object, speed) {
    var X = Math.floor((position.x) / speed - 20) + "px";
    var Y = Math.floor((position.y) / speed) + "px";
    object.css('transform', 'translate(' + X + ' , ' + Y + ')');
}

function step(timestamp) {
    moveAll(imgs);
    window.requestAnimationFrame(step);
}

function moveAll(object) {
    moving($(object[0]), 12);
    moving($(object[1]), 22);
    moving($(object[2]), 8);
    moving($(object[3]), 10);
    moving($(object[4]), 20);
}
showAllObjects(imgs);

window.requestAnimationFrame(step);