Кроссбраузерная реверсивная анимация фона на CSS3

в 17:22, , рубрики: animations, css, css3, html5, JS, веб-дизайн, Веб-разработка, метки: , ,

Доброго времени суток уважаемые читатели Хабра. Существуют замечательные CSS свойства с помощью которых можно задать реверсивное движение анимации — animation-direction: alternate и animation-direction: alternate-reverse (не путать со свойством animation-direction: reverse, которое задает реверсивное направление), но на сегодняшний день их не поддерживает большинство современных браузеров. Я хочу рассказать о том как сделать кроссбраузерную реверсивную анимацию фона.

netcribe

Пример на Jsfiddle


HTML

<html>
<head></head>
<body id="body"><body>
</html>

CSS

Задаем цвет фона (pattern.png — текстура в данном примере) и высоту страницы равную высоте окна браузера:

html{
   height: 100%;
   min-height: 100%;
}
body{
   background:url('https://www.netcribe.com/images/pattern.png') repeat fixed left center #0296BA;
   overflow:hidden;
}

Анимированная часть фона — иконки, изображение которых будет бэкграундом элементов с классом .icons. Ширина равна ширине фонового изображения.

leadicons.png (4898px * 32px)
иконки

.icons{
background-image:url('https://www.netcribe.com/images/leadicons.png');
background-repeat:repeat-x;
height:60px;
width:4898px;
clear:both;
/*animation-duration*/
-webkit-animation-duration:200s;
   -moz-animation-duration:200s;
    -ms-animation-duration:200s;
     -o-animation-duration:200s;
        animation-duration:200s;
/*animation-iteration-count*/
-webkit-animation-iteration-count:infinite;
   -moz-animation-iteration-count:infinite;
    -ms-animation-iteration-count:infinite;
     -o-animation-iteration-count:infinite;
        animation-iteration-count:infinite;
}

В CSS указаны два класса movement-left, которому присвоена анимация с движением влево и movement-right, которому присвоена анимация с движением вправо:

.move-left{
/*animation-name*/
-webkit-animation-name:movement-left;
   -moz-animation-name:movement-left;
    -ms-animation-name:movement-left;
     -o-animation-name:movement-left;
        animation-name:movement-left; 
}

.move-right{
/*animation-name*/
-webkit-animation-name:movement-right;
   -moz-animation-name:movement-right;
    -ms-animation-name:movement-right;
     -o-animation-name:movement-right;
        animation-name:movement-right; 
}

Javascript

Важно чтобы движение элементов с классом .icons начиналось с разных позиций, поэтому у всех элементов должны быть разные свойства background-position, а в самих функциях анимации изменяться свойство margin.

CSS стили с использованием animation-direction:

.icons{
background-image:url('https://www.netcribe.com/images/leadicons.png');
background-repeat:repeat-x;
height:60px;
width:4898px;
clear:both;

/*animation-duration*/
-webkit-animation-duration:200s;
   -moz-animation-duration:200s;
    -ms-animation-duration:200s;
     -o-animation-duration:200s;
        animation-duration:200s;
/*animation-iteration-count*/
-webkit-animation-iteration-count:infinite;
   -moz-animation-iteration-count:infinite;
    -ms-animation-iteration-count:infinite;
     -o-animation-iteration-count:infinite;
        animation-iteration-count:infinite;
/*animation-name*/
-webkit-animation-name:movement;
   -moz-animation-name:movement;
    -ms-animation-name:movement;
     -o-animation-name:movement;
        animation-name:movement; 	
}

.move-left{
/*animation-direction*/
-webkit-animation-direction:alternate;
   -moz-animation-direction:alternate;
    -ms-animation-direction:alternate;
     -o-animation-direction:alternate;
        animation-direction:alternate;	
}

.move-right{
/*animation-direction*/
-webkit-animation-direction:alternate-reverse;
   -moz-animation-direction:alternate-reverse;
    -ms-animation-direction:alternate-reverse;
     -o-animation-direction:alternate-reverse;
        animation-direction:aalternate-reverse;	
}

В этом случае значительно бы сократился javascipt код

<script src="http://yandex.st/jquery/1.8.2/jquery.min.js"></script>

$(document).ready(function(){
    var clientWidth, clientHeight, x, y, z;
    clientWidth = $("html").width();
    clientHeight = $("html").height();
    margin = 4898 - parseInt(clientWidth);
    x=Math.ceil(clientHeight/60); // Целое число элементов с классом .icons требуемых для заполнения страницы по высоте
    y=0; // Разные значения свойства background-position
    z=Math.ceil(4898/(2*x)); // Оптимальная разцица значений background-position
    $("#body").css({'width':clientWidth,'height':clientHeight});

Генерируем функции анимации:

    $("#body").append('<style>@keyframes movement-left {from {} to {margin-left: '+ -margin +'px;}} @keyframes movement-right {from {} to {margin-left: 0px;} @-moz-keyframes movement-left {from {} to {margin-left: '+-margin+'px;}} @-moz-keyframes movement-right {from {} to {margin-left:0px;} @-ms-keyframes movement-left {from {} to {margin-left: '+ -margin +'px;}} @-ms-keyframes movement-right {from {} to {margin-left: 0px;}} @-o-keyframes movement-left {from {} to {margin-left: '+ -margin +'px;}} @-o-keyframes movement-right {from {} to {margin-left: 0px;}} @-webkit-keyframes movement-left {from {} to {margin-left: '+ -margin +'px;}} @-webkit-keyframes movement-right {from {} to {margin-left: 0px;}} </style>');

Создаем элементы с классом .icons:

for(var i=0;i<x;i++){
    if(i%2==0){
        $("#body").append('<div style="background-position:'+y+'px 0;" class="icons move-left">');
    } else{
        $("#body").append('<div style="background-position:'+y+'px 0; margin-left: '+ -margin +'px" class="icons move-right">');}y+=z;}
});
Зачем изменять margin, когда можно изменять только background-position:
В этом случае расстояние до финальной позиции указанной в background-position у всех элементом будет разное, как и скорость движения. Из за чего анимация выглядит ужасно

Принцип Цикады

Реализовать данный пример возможно, используя одну анимацию, в которой будет изменяться только background-position. В этом случае потребуется воспользоваться замечательным Принципом Цикады (подробнее об этом написано здесь). После чего указать реверсивное движение анимации.

Спасибо всем за внимание

Автор: ilusha_sergeevich

Источник

* - обязательные к заполнению поля


https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js