Buscar..


Sintaxis

  • window.requestAnimationFrame ( callback );
  • window.webkitRequestAnimationFrame ( callback );
  • window.mozRequestAnimationFrame ( callback );

Parámetros

Parámetro Detalles
llamar de vuelta "Un parámetro que especifica una función a la que llamar cuando sea el momento de actualizar su animación para el próximo repintado". ( https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)

Observaciones

Cuando se trata de animar elementos DOM de manera fluida, estamos limitados a las siguientes transiciones CSS:

  • POSICIÓN - transform: translate (npx, npx);
  • ESCALA - transform: scale(n) ;
  • ROTACIÓN - transform: rotate(ndeg);
  • OPACIDAD - opacity: 0;

Sin embargo, el uso de estos no garantiza que las animaciones sean fluidas, ya que hace que el navegador inicie nuevos ciclos de paint , independientemente de lo que esté sucediendo. Básicamente, la paint se hace de manera ineficiente y su animación se ve "janky" porque los cuadros por segundo (FPS) sufren.

Para garantizar animaciones de DOM sin problemas, requestAnimationFrame debe usarse junto con las transiciones de CSS anteriores.

La razón por la que funciona, es porque la API requestAnimationFrame permite al navegador saber que desea que ocurra una animación en el próximo ciclo de paint , en lugar de interrumpir lo que está sucediendo para forzar un nuevo ciclo de pintura cuando se llama una animación que no es de la RAF .

Referencias URL
Que es jank http://jankfree.org/
Animaciones de alto rendimiento http://www.html5rocks.com/en/tutorials/speed/high-performance-animations/ .
CARRIL https://developers.google.com/web/tools/chrome-devtools/profile/evaluate-performance/rail?hl=es
Análisis de la ruta de representación crítica https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp?hl=es
Rendimiento de representación https://developers.google.com/web/fundamentals/performance/rendering/?hl=es
Analizando tiempos de pintura https://developers.google.com/web/updates/2013/02/Profiling-Long-Paint-Times-with-DevTools-Continuous-Painting-Mode?hl=es
Identificación de cuellos de botella de pintura https://developers.google.com/web/fundamentals/performance/rendering/simplify-paint-complexity-and-reduce-paint-areas?hl=es

Utilice requestAnimationFrame para fundirse en el elemento

<html>
    <body>
        <h1>This will fade in at 60 frames per second (or as close to possible as your hardware allows)</h1>
        
        <script>
            // Fade in over 2000 ms = 2 seconds.
            var FADE_DURATION = 2.0 * 1000; 
            
            // -1 is simply a flag to indicate if we are rendering the very 1st frame
            var startTime=-1.0; 
            
            // Function to render current frame (whatever frame that may be)
            function render(currTime) { 
                var head1 = document.getElementsByTagName('h1')[0]; 
            
                // How opaque should head1 be?  Its fade started at currTime=0.
                // Over FADE_DURATION ms, opacity goes from 0 to 1
                var opacity = (currTime/FADE_DURATION);
                head1.style.opacity = opacity;
            }
            
            // Function to 
            function eachFrame() {
                // Time that animation has been running (in ms)
                // Uncomment the console.log function to view how quickly 
                // the timeRunning updates its value (may affect performance)
                var timeRunning = (new Date()).getTime() - startTime;
                //console.log('var timeRunning = '+timeRunning+'ms');
                if (startTime < 0) {
                    // This branch: executes for the first frame only.
                    // it sets the startTime, then renders at currTime = 0.0
                    startTime = (new Date()).getTime();
                    render(0.0);
                } else if (timeRunning < FADE_DURATION) {
                    // This branch: renders every frame, other than the 1st frame,
                    // with the new timeRunning value.
                    render(timeRunning);
                } else {
                    return;
                }
            
                // Now we're done rendering one frame.
                // So we make a request to the browser to execute the next
                // animation frame, and the browser optimizes the rest.
                // This happens very rapidly, as you can see in the console.log();
                window.requestAnimationFrame(eachFrame);
            };
            
            // start the animation
            window.requestAnimationFrame(eachFrame);    
        </script>
    </body>
</html>

Cancelando una animacion

Para cancelar una llamada a requestAnimationFrame , necesita la ID que devolvió cuando se llamó por última vez. Este es el parámetro que utiliza para cancelAnimationFrame . El siguiente ejemplo inicia una animación hipotética y luego la detiene después de un segundo.

// stores the id returned from each call to requestAnimationFrame
var requestId;

// draw something
function draw(timestamp) {
    // do some animation
    // request next frame
    start();
}

// pauses the animation
function pause() {
    // pass in the id returned from the last call to requestAnimationFrame
    cancelAnimationFrame(requestId);
}

// begin the animation
function start() {
    // store the id returned from requestAnimationFrame
    requestId = requestAnimationFrame(draw);
}

// begin now
start();

// after a second, pause the animation
setTimeout(pause,1000);

Manteniendo la compatibilidad

Por supuesto, al igual que la mayoría de las cosas en el navegador JavaScript, no puedes contar con el hecho de que todo será igual en todas partes. En este caso, requestAnimationFrame puede tener un prefijo en algunas plataformas y se nombran de forma diferente, como webkitRequestAnimationFrame . Afortunadamente, hay una manera realmente fácil de agrupar todas las diferencias conocidas que podrían existir en una función:

window.requestAnimationFrame = (function(){
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function(callback){
            window.setTimeout(callback, 1000 / 60);
        };
})();

Tenga en cuenta que la última opción (que se completa cuando no se encontró un soporte existente) no devolverá una identificación para ser utilizada en cancelAnimationFrame . Hay, sin embargo, un eficiente polyfill que fue escrito que corrige esto.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow