Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Синхронизируем таймеры анимаций используя Web Animation API</h1>
<p>Это демо для <a href="http://frontender.info/the-state-of-animation-2014/">перевода статьи Smashing Magazine об использовании веб-анимаций.</a> Оно использует <a href="https://github.com/web-animations/web-animations-js">полифил</a> Web Animation API. (Пссс: посмотрите JavaScript и CSS что бы узнать, как это было сделано.) Что бы узнать больше о Web Animation API, <a href="http://rachelnabors.com/waapi/">загляните на моб страничку со ссылками на материалы по WAAPI!</a></p>
<div id="CSSCats">
  <h2>Кот анимирован с помощью <br />CSS-анимаций</h2>
  <p>На сегодняшний день невозможно синхронизировать две CSS анимации. Добавьте новых котов, анимированных с помощью CSS и обратите внимание — они не будут бежать абсолютно синхронно.</p>
  <div class="cat withCSS"></div>
  <button onclick="animateNewCatWithCSS()">Добавь кота</button>
</div>

<div id="WAAPICats">
  <h2>Кот анимирован с помощью <br />Web Animation API</h2>
  <p>С помощью Web Animation API, можно задать значение <code>startTime</code> для анимаций и полностью их синхронизировать. Когда вы добавляете котов, анимированных с помощью Web Animation API, они бегут синхронно, шаг в шаг!</p>
  <div class="cat" id="withWAAPI"></div>
  <button onclick="animateNewCatWithWAAPI()">Добавь кота</button>
</div>
              
            
!

CSS

              
                /* У всех котов одинаковые размеры и спрайт в качестве фонового изображения. */
.cat {
  background: url(http://stash.rachelnabors.com/24ways2012/cat_sprite.png) -800px 0 no-repeat; 
  height: 200px; width: 400px;
}

/* У кота, анимированного с помощью CSS, анимация бега определяется с помощью CSS. */
.cat.withCSS {
  animation: run-cycle;
  animation-duration: .75s;
  animation-timing-function: steps(13,end);
  animation-iteration-count: infinite;
}

/* Ключевые кадры для анимации бега.
   Они смещают спрайт, установленный в качестве фонового изображения. */
@keyframes run-cycle {  
  0% {background-position: -800px 0; }
  100% {background-position: -800px -2591px; } 
}

/* Что бы узнать больше о том, как использовать спрайты прочтите мою статью для проекта 24 Ways: 
   http://24ways.org/2012/flashless-animation/ */

/* Дальще только описание представления. 
   Ничего интересного! */
#CSSCats, #WAAPICats {
  display: inline-block;
  text-align: center;
  vertical-align: top;
  width: 400px;
}

@media only screen and (min-width: 850px) {

  #CSSCats, #WAAPICats {
    margin: 3em 0;
  }
}

#CSSCats p, #WAAPICats p {
  text-align: left;  
}

body { 
  background: #e5e6e9;
  color: #071933;
  font-family: 'Lato', sans-serif;
  font-size: 1em; 
  line-height: 1.5em;
  margin: 1em 0;
  text-align: center;
  width: 100%;
}

@media only screen and (min-width: 850px) { 
  body {
    margin: 4em auto;
    width: 80%;
  }
}
h1 {
  font-family: 'Aleo', sans-serif;
  font-weight: 200;
  font-size: 2em;
  line-height: 1.25em;
}

h2 {
  font-family: 'Aleo', sans-serif;
  font-weight: 400;
  font-size: 1.5em;
  line-height: 1.25em;  
}

p {
  margin: .5em 0;
}

button {
  background: #2d0d3c;
  border: 0;
  color: #f7e6ff;
  cursor: pointer;
  font-size: .9em;
  padding: .7em 2em;
}

@media only screen and (min-width: 850px) { 
  button {
    padding: 1em 0;
    font-size: 1em;
  }
}

code { font-family: monospace;}

a:link { color: #1954c0; } a:visited {color: #702096; }
a:hover, a:active, a:focus {
  color: #646d97;
}


              
            
!

JS

              
                // Создаем объект с ключевыми кадрами, содержащий тот же набор значений, что и в  '@keyframes' правиле в CSS

var keyframes = [
  {backgroundPosition: "-800px 0"},
  {backgroundPosition: "-800px -2591px"}
];

// и объект для управления временем, который содержит те значения, которые мы обычно задаем в правиле 'animation' CSS

var timing = {
  duration: 750,
  iterations: Infinity,
  easing: "steps(13, end)"
};

/* с помощью функции анимации, представленной WAAPI применяем оба объекта к елементу .cat#withWAAPI (Вы можете найдите его с помощью DOM-инспектора!)*/

var catRunning = document.getElementById ("withWAAPI").animate(keyframes, timing);

/* Функция создающая новых котов!
   Крутотенюшка! Мы используем её ниже. */

function addCat(){
  var newCat = document.createElement("div");
  newCat.classList.add("cat");
  return newCat;
}

/* Это функция, которая добавляет кота в блок с CSS-решением */
function animateNewCatWithCSS() {
  // Создаем кота
  var newCat = addCat();
  // Добавляем CSS-класс, который запускает CSS-анимацию
  newCat.classList.add("withCSS");
  CSSCats.appendChild(newCat);
}

/* Эта функция добавляет кота в блок, где для анимации используется WAAPI */

function animateNewCatWithWAAPI() {
  // Создаем кота
  var newCat = addCat();
  // Анимируем его с помощью функции "animate" WAAPI
  var newAnimationPlayer = newCat.animate(keyframes, timing);
  // Создаем объект плеера, что бы задать тот же момент времени начала проигрывания, что и у оригинального .cat#withWAAPI
  newAnimationPlayer.startTime = catRunning.startTime;
  WAAPICats.appendChild(newCat);
}
              
            
!
999px

Console