Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Web Animation API

Web Animation API

Tanto tempo fa quando ti chiedevano un sito dinamico, intendevano una roba con la intro fatta in flash. Molto è cambiato da allora, vuoi per il trauma di intro così pesanti, vuoi per la difficile implementazione. Qualunque sia il motivo, di fatto l'animazione è diventata un cittadino di seconda categoria.

Le Web Animation API sono qui per cambiare le carte in tavola. Scopriremo non solo il come ma anche il perché dietro le Web Animation API e come utilizzarle da subito.

Davide Di Pumpo

October 03, 2017
Tweet

More Decks by Davide Di Pumpo

Other Decks in Technology

Transcript

  1. Milano JS
    Web Animation API
    The vengeance

    View Slide

  2. View Slide

  3. View Slide

  4. Davide Di Pumpo
    Full stack designer (?)
    Senior Frontend developer at
    Co-organizer
    MakhBeth on: , ,
    I like Cats, Scotch, Comics and
    Videogames...
    Credimi
    Milano Frontend
    Twitter Github Internet

    View Slide

  5. LET'S START MEOW

    View Slide

  6. Cosa sono?
    The Web Animations API provides a common language for
    browsers and developers to describe animations on DOM
    elements.
    MDN

    View Slide

  7. Come animiamo oggi?
    (In classi ca)
    o librerie come e
    setInterval
    jQuery.animate()
    requestAnimationFrame()
    CSS animations GSAP Velocity

    View Slide

  8. Set interval

    View Slide

  9. var elem = document.getElementById("animatedElem");
    var left = 0;
    var lastFrame = +new Date;
    var timer;
    timer = setInterval(function() {
    var now = +new Date,
    deltaT = now - lastFrame;
    elem.style.left = ( left += 10 * deltaT / 16 ) + "px";
    lastFrame = now;
    if ( left > 400 ) {
    clearInterval( timer );
    }
    }, 16);

    View Slide

  10. Set interval
    seriamente?
    Impreciso
    Prestazionalmente osceno
    Comodo da usare come un registratore betamax

    View Slide

  11. jQuery Animate

    View Slide

  12. $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
    }, 5000, function() {
    // Animation complete.
    });

    View Slide

  13. jQuery Animate
    < 3.0 Usa setInterval
    È utile solo se usate già jQuery
    Sì ok, ma state usando jQuery?

    View Slide

  14. Request
    Animation Frame

    View Slide

  15. var start = null;
    var element = document.getElementById('SomeElementYouWantToAnimate');
    element.style.position = 'absolute';
    function step(timestamp) {
    if (!start) start = timestamp;
    var progress = timestamp - start;
    element.style.left = Math.max(progress / 10, 200) + 'px';
    if (progress < 2000) {
    window.requestAnimationFrame(step);
    }
    }
    window.requestAnimationFrame(step);

    View Slide

  16. Request Animation Frame
    Ancora troppo boilerplate
    Il prossimo repaint non vuol dire avere 60fps
    L'animazione è nita? Voglio modi carla? Voglio cambiare
    easing?

    View Slide

  17. CSS

    View Slide

  18. .................I poteri forti hanno censurato questo snippet..................
    ..................~~,.............,~,...............................:...........
    ......................:??777O88II7:..........:~~..............................,:
    ...................,=7II?I77$778$I?I~........:~~..............................,:
    .................+7$$Z77Z$77$O8Z7$Z7?~:......:~~..............................,~
    ...............~I$77O$77$$8DDDDD8OZ7ZZ=:.....:~~......~~..............:~:.....,~
    ..............+ZZ$$O8$$7N8D8DDDD8D7Z$7=?:,...:~~......~~..............:~~.....,~
    .............$$DOOZZD7ZO8DD8DDDDDDD8IZZ?~:~..:~~......~~.......,......~~~.....,~
    ............77O8ZODZ8OZ$OO888DNNDDO8DD7Z=I==.:~~......~~,.....~~:.....~~~.....,~
    ...........=$$7ZZ7$Z$$OZ8OOZZZ$ZOO8OZO77+=7I::~~......~~,.....~~:.....~~~.....,~
    ...........7$$7$7$OZOZZZ$$$$77IIII77$7++~::Z$:=~......~~,.....~~~.....~~~.....,~
    ...........7Z7$$$OOZ$7I??II7I7I7IIIIIII+=~,?O:~~..............................,~
    ...........$$$Z$8887===?+II7I77IIIIIII??=~:,8~~~..............................,~
    ...........7$$Z$OOO$===++IIII7IIIIII?=~=~~~,Z,..................................
    ...........I$$O88ZO$+~~=??IIIIIIIIIII??=:,,,O...................................
    ...........=$788ZZ8$=~~~=+?$$$$7777I77Z$ZZ7+7=..................................
    ............Z$O8ZOZ=~~:~IO8DDDDDO$7I7Z8NDD7?~=..................................
    ............O7ZO787=~::?7ZO8D888OO7II8888$Z?.?..:==.....,=====~......~=~==~~....
    ............77$ZZZI~:::?7ZI8O7OOZOI+,Z$ZZ7II,7..,==....,==~........,===~,.,:....
    ............7$=?I$I~::=I$7I$ZOOZZI++==ZZ$I+:.=..,==,....===,.......===.........:
    ...........,$+I=~7=:::~+?II77$$7?+=~=,+77I::,:..,==,....,=====:....===.........~
    ............$+IZ=~+::::=+?I77777?=~~?:=+II?+~,..,==,........~==:...===.........:
    ............+I$7+?=I:::=?II77777?~,+I+,+??++:~..,==,........:==~...,====,,:~....
    .............:?7+I??+:~=+II77777~I:?II++I??77:..,==,...,======~......~======....
    ..............=,+?7=+~~+?IIIII77$$Z7I$?=?I+I=..,.........,,,....................
    ...............:~+?~=:+???I??7II$ZOOO$7?+++Z?...................................
    ..................,~+=+77II+77I$ZO888ZO$$$?$I...................................
    ..................?:++I$$I=?ZOZ77$$$$IINOO?I....................................
    ...................,~++I77IIZOZOO88888Z?$ZI?....................................
    ....................:++?I7??$Z$7I7$$$$I+$$+.....................................
    ....................:=====?+?$$$$$O88Z7IZI,.....................................
    ....................,:===~=+77ZZZ$ZZZZI7$+......................................
    .................,...:~=?=+$+7ZOOOOZZO8ZI:.... .................................
    .................~...:~=++~~++ZO888OO8O7=:,.....................................
    .....................,:~=++===I$Z777Z$$I=~,....dovrebbe essere..................
    .....................,,:~?I+~=+I7?7$Z$7?+=.....l'avatar di granze...............
    ............:.::::..,,,:~+?+~=?II7$$$7??.,......................................
    ....................,,,,~++++=II77777+:::,......................................
    ................,.....,,:=+??+I7$?=~~:::,......................................

    View Slide

  19. CSS
    Sono ok per la maggiorparte dei casi ma:
    Non possono essere composte sullo stesso elemento
    È dif cile lanciarle in parallelo
    È impossibile animare valori che cambiano dinamicamente
    (provate un vertical accordion con testo ed height auto)!

    View Slide

  20. Ok se fate un utilizzo massivo di animazioni del progetto, ma:
    Librerie esterne
    Come se non avessimo già abbastanza dipendenze
    È comunque una libreria esterna
    Probabilmente state sparando ad una mosca con un
    cannone
    Per quanto ne dica GSAP (140kB) non sono uno standard

    View Slide

  21. Quindi?
    ste uebbe animescion apiai?

    View Slide

  22. vediamo un po' di codice

    View Slide

  23. var player = document.getElementById('toAnimate').animate([
    { transform: 'scale(1)', opacity: 1, offset: 0 },
    { transform: 'scale(.5)', opacity: .5, offset: .3 },
    { transform: 'scale(.6)', opacity: .6, offset: 1 }
    ], {
    duration: 700, //milliseconds
    easing: 'ease-in-out', //'linear', a bezier curve, etc.
    delay: 10, //milliseconds
    iterations: Infinity, //or a number
    direction: 'alternate', //'normal', 'reverse', etc.
    fill: 'forwards' //'backwards', 'both', 'none', 'auto'
    });

    View Slide

  24. Un pelo più dichiarative, così dichiarative che potremmo
    scriverle in puro CSS

    View Slide

  25. @keyframes emphasis {
    0% {
    transform: scale(1);
    opacity: 1;}
    30% {
    transform: scale(.5);
    opacity: .5;}
    100% {
    transform: scale(.6);
    opacity: .6;}
    }
    #toAnimate {
    animation: emphasis 700ms ease-in-out 10ms infinite alternate forwards;
    }
    Senza timore dei poteri forti

    View Slide

  26. var player = document.getElementById('toAnimate').animate([
    { transform: 'scale(1)', opacity: 1, offset: 0 },
    { transform: 'scale(.5)', opacity: .5, offset: .3 },
    { transform: 'scale(.6)', opacity: .6, offset: 1 }
    ], {
    duration: 700, //milliseconds
    easing: 'ease-in-out', //'linear', a bezier curve, etc.
    delay: 10, //milliseconds
    iterations: Infinity, //or a number
    direction: 'alternate', //'normal', 'reverse', etc.
    fill: 'forwards' //'backwards', 'both', 'none', 'auto'
    });

    View Slide

  27. View Slide

  28. Andando un po' più a fondo
    var animation = element.animate(keyframes, options);

    View Slide

  29. oppure:
    keyframes
    È un oggetto che contiene tutte le proprietà animabili, può
    essere formattato in due modi:
    element.animate({
    opacity: [ 0, 1 ], // [ from, to ]
    color: [ "#fff", "#000" ] // [ from, to ]
    }, 2000);
    element.animate([
    { // from
    opacity: 0,
    color: "#fff"
    },
    { // to
    opacity: 1,
    color: "#000"
    }
    ], 2000);

    View Slide

  30. options
    Un intero che rappresenta la durata dell'animazione in
    millisecondi oppure un oggetto che contiene una o più delle
    seguenti proprietà:
    id
    delay
    direction
    duration
    easing
    endDelay
    fill
    iterationStart
    iterations

    View Slide

  31. Sì, in pratica sono le proprietà
    animation- del CSS esposte
    su JS

    View Slide

  32. E n qua è quasi CSS in JS

    View Slide

  33. La console di Chrome

    View Slide

  34. Esatto, ritorna un oggetto di tipo Animation con
    i propri metodi e proprietà. Ed è qui che arriva il bello!
    animate()

    View Slide

  35. Metodi
    cancel() torna allo stato iniziale
    finish() salta alla ne del dell'animazione
    pause() mette l'animazione in pausa
    play() mette l'animazione in esecuzione
    reverse() riproduce l'animazione al contrario

    View Slide

  36. Proprietà
    currentTime mostra/setta il tempo di esecuzione in ms
    id ritorna l'id
    oncancel esegue una funzione quando l'animazione viene
    cancellata dall'apposito metodo
    onfinish esegue una funzione quando l'animazione
    termina
    playbackRate la "velocità" dell'animazione, può essere
    negativa
    playState mostra/setta lo stato di esecuzione
    startTime

    View Slide

  37. Promise
    //set up 1 second animation to fade box out
    var box = document.getElementById('box');
    var animation = box.animate([{ opacity: 1 }, { opacity: 0 }], 1000);
    function finishedHandler() {
    console.log('animation finished: ' + Date.now());
    }
    function canceledHandler() {
    console.log('animation canceled: ' + Date.now());
    }
    //the Promise version, log the timestamp when the Animation finishes
    animation.finished.then(finishedHandler, canceledHandler);
    //the effective successful equivalent with the onfinish callback
    animation.onfinish = finishedHandler;
    Dan Wilson

    View Slide

  38. Promise
    finished
    ready

    View Slide

  39. Altre cosucce da sapere

    View Slide

  40. Un elemento può ovviamente avere più
    animazioni
    var animated = document.getElementById('cat');
    var purr = animated.animate({}, 1000);
    var rotate = animated.animate({}, 2000);
    var jump = animated.animate({}, 3500);

    View Slide

  41. Potete vedere tutte le animazioni presenti
    attraverso il metodo:
    document.getAnimations()

    View Slide

  42. Perchè e quando
    usarle?

    View Slide

  43. #OpinionePersonale
    Se l'animazione è funzionale va in JS, se è estetica nel CSS

    View Slide

  44. Un , un una , un fanno
    della loro comparsa un motivo d'esistere
    accordion tooltip sidebar dropdown
    L'effetto hover su un bottone è enhancement

    View Slide

  45. Ci sono alcuni casi come l' la in base alla
    viewport o ad altri elementi in pagina, in cui JS è necessario
    altezza posizione

    View Slide

  46. LA POTENZA È
    NULLA SENZA
    CONTROLLO

    View Slide

  47. View Slide

  48. Ma veniamo al momento da tutti agognato!
    Il momento del ricordo

    View Slide

  49. View Slide

  50. È possibile
    animare su un
    path!!1!1

    View Slide

  51. MilanoJS
    var path = `path("M300.358,297.675c55.955,57.158 83.03,107.698 141.392,107.698c58
    var p = document.getElementById('cat2');
    var animation = p.animate({
    offsetPath: [path, path ],
    offsetDistance: [0, "100%"]
    }, {
    duration: 4000,
    iterations: Infinity
    });

    View Slide

  52. Utilizzarle oggi?

    View Slide

  53. View Slide

  54. Ma abbiamo un poly ll

    View Slide

  55. e iniziano ad apparire progetti interessanti

    View Slide

  56. react-web-animation

    View Slide

  57. import { Component } from 'react';
    import { Animated } from 'react-web-animation';
    export default class Basic extends Component {
    getKeyFrames() {
    return [
    { transform: 'scale(1)', opacity: 1, offset: 0 },
    { transform: 'scale(.5)', opacity: 0.5, offset: 0.3 }
    { transform: 'scale(.6)', opacity: 0.6, offset: 1 }
    ];
    }
    getTiming( duration ) {
    return {
    duration,
    easing: 'ease-in-out',
    delay: 0,
    iterations: 2,
    direction: 'alternate'

    View Slide

  58. Spe, parlando di performance?

    View Slide

  59. CSS-based animations, and Web Animations where
    supported natively, are typically handled on a thread known
    as the "compositor thread". This is different from the
    browser's "main thread", where styling, layout, painting, and
    JavaScript are executed. This means that if the browser is
    running some expensive tasks on the main thread, these
    animations can keep going without being interrupted.
    Google developers

    View Slide

  60. Quindi?

    View Slide

  61. Il web non è un le .sketch o .psd, la user interface può trarre
    grandi vantaggi dalle animazioni
    Plz, possiamo usarle, facciamolo.

    View Slide

  62. View Slide

  63. Credit: Colin Garven

    View Slide

  64. View Slide

  65. Bibliography
    Mozilla Developers Network
    Chrome platform status
    WAAPI Tutorial
    Intro to WAAPI
    Exploring WAAPI
    Motion in UX

    View Slide