requestAnimationFrame for begining a CSS transition
Asked Answered
K

2

7

Does it make sense to request an animation frame for beginning a CSS transition?

For example, the Mozilla CSS transitions page includes a link to this jsfiddle example:

CSS:

#foo{
    border-radius:50px;
    width:50px;
    height:50px;
    background:#c00;
    position:absolute;
    top:0;
    left:0;
    -moz-transition: all 1s;
    -webkit-transition: all 1s;  
    -ms-transition: all 1s;  
    -o-transition: all 1s;  
    transition: all 1s;  
}

JavaScript:

var f = document.getElementById('foo');
document.addEventListener('click', function(ev){
    f.style.left = (ev.clientX-25)+'px';
    f.style.top = (ev.clientY-25)+'px';
},false);    

Does rewriting this example as follows make any sense? (See this jsfiddle)

JavaScript:

var rAF = window.mozRequestAnimationFrame ||
          window.webkitRequestAnimationFrame;
var f = document.getElementById('foo');
document.addEventListener('click', function(ev){
    rAF(function() {
        f.style.left = (ev.clientX-25)+'px';
        f.style.top = (ev.clientY-25)+'px';
    });
},false);

Thanks for any answer.

Kayak answered 25/10, 2012 at 20:15 Comment(2)
I don't think so. The browser should do that on its own. You might be even delaying it by one frame.Macintyre
Having the same question at the moment... Any new insights? Guess it is like @IanKuca wrote but I'd love to have a more profund answer :)Mcallister
S
4

I know question is old, but this may be useful for somebody.

rAF(requestAnimationFrame) is useless in this example. Because you are sliding element with css transition and calling rAF once. You have to loop prop changes with calling rAF frame by frame for optimize CPU,GPU performance by browser.

Main idea about rAF:

When you want to animate dom elements without css animations, you have to change elements' style properties (like width, height, top, left etc.) periodically.

Without rAF, you have to use setTimeout, setInterval functions to change props according to time. But browsers don't optimize these processes and it can be painful for CPU,GPU performance.

When you use rAF, modern browsers can optimize animation performance with less CPU, GPU usage.

Useful Links:

requestAnimationFrame for Smart Animating

requestAnimationFrame

Sterculiaceous answered 2/4, 2015 at 11:13 Comment(0)
R
4

No it does not. In modern browsers all animations, CSS transitions, CSS animations, SMIL, element.animate are controlled by the same internal engine. Browsers will start your animation on the next available frame. RAF and native animate have different threads. RAF is meant for JavaScript animations. That rewrite will just wait few milliseconds until setting those changes. After that your animation will be controlled by the internal engine.

Romanaromanas answered 2/4, 2015 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.