javascriptjqueryanimationeasing-functions

How to add an easing function to increase a variable value during animation


I am looking for some math genius to help me with this one:

I have a quite simple keyframe js animation:

var i = 0;
var o = 0; // opacity
var y_frames = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H"];   

function draw_y() {

    requestAnimationFrame( draw_y );
    // drawing
    if ( i < y_frames.length ) {  
        $y  .text( y_frames[i] )
            .css( { opacity: o } );
        i++;
        o += 0.03;
    } else {
        // code to be executed when animation finishes
    }
};
draw_y();

In addition to stepping the keyframes I add some opacity until it reaches the value 1. This works very well and very smooth. So far so good. What I would like to add is some easeOutSine to the increment of the opacity value. I know that this is possible by using this function:

function easeOutSine(t, b, c, d) {
    return c * Math.sin(t/d * (Math.PI/2)) + b;
}

but I need some help how to combine the two. How can I do this? Anyone who did this before me? Thanks a lot!

Garavani


Solution

  • This is how you combine both functions

    var i = 0;
    var o = 0; // opacity
    var y_frames = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H",];   
    function draw_y() {
        // drawing
        if ( i < y_frames.length ) { 
            o = easeOutSine( i , 0 , 1, y_frames.length);
            $y  .text( y_frames[i] )
                .css( { opacity: o } );
            i++;
            window.requestAnimationFrame( draw_y );
        } else {
            // code to be executed when animation finishes
        }
    };
    
    function easeOutSine(t, b, c, d) {
        return c * Math.sin(t/d * (Math.PI/2)) + b;
    }
    window.requestAnimationFrame( draw_y );
    

    Note: Always call the requestAnimationFrame inside the condition or it will keep running infinitely.