JavaScript Animation with timings

Made by Marvin Drude

JavaScript Animation with timings

I see alot of people use big bloated libraries to animate HTML. Besides having the option to do alot of those things with pure CSS, you might still want to have the control using JavaScript to have more possibilities.

I am going to show you the whole code first and after that I am going to go into detail. Keep in mind that I want to give a simple introduction in the topic, so I won’t cover everything and have every possible feature implemented.

var animate = function() {

    // arguments or empty object
    var args = arguments[0] || { };

    // if no timing function is given, just use linear
    args.timing = args.timing || function(x) { return x; }
    // if no duration given, use 500ms
    args.duration = args.duration || 500;
    // there should always be a render function
    args.render = args.render || function(p) { };
    // callback when finished
    args.end = args.end || function() { };

    // get start time
    var start = performance.now();

    requestAnimationFrame(function animate(time) {

        // fraction in percent for example 0.4 for 40%
        var fraction = (time - start) / args.duration;

        // if fraction is bigger than 100% set it to 100%
        if(fraction > 1) {
            fraction = 1;
        }

        // just to make sure that its never less than 0%
        if(fraction < 0) {
            fraction = 0;
        }

        // convert linear progress (fraction) to timing progress
        var progress = args.timing(fraction);
        args.render(progress);

        if(fraction < 1) {
            // continue loop
            requestAnimationFrame(animate);
        } else {
            // animation finished
            args.end();
        }

    });

}

It is important to know that really old browsers do not support requestAnimationFrame and performance.now(). Now let’s see a example usage of this function.

var rectangle = document.getElementById("ex-rect-1");

animate({
    "timing": function(x) {
        return x;
    },
    "duration": 5000,
    "render": function(x) {
        rectangle.style.left= (x * 100) + "%";
    }
});

Timings

We can also try out different timing function to get all sorts of amazing effects.

function(x) { return x * x; }
function(x) { return x * x * x * x * x; }
function (x) { return (--x) * x * x + 1; }
function(x) { return x < 0.5 ? 16 * x * x * x * x * x : 1 + 16 * (--x) * x * x * x * x; }