Skip to content

Instantly share code, notes, and snippets.

@molokoloco
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save molokoloco/16fdddf807c81f576ac4 to your computer and use it in GitHub Desktop.
Save molokoloco/16fdddf807c81f576ac4 to your computer and use it in GitHub Desktop.
JS animations techniques
// Simple anim
var fps = 1000/60;
var tick = function () {
// animate something
if (notFinish) setTimeout(tick, fps);
};
tick();
// Cross-browsers "requestAnimationFrame"
// http://gist.github.com/paulirish/1579671
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// And then...
var tick = function () {
if (notFinish) requestAnimFrame(tick);
// animate something
};
tick();
// A more sophisticated technique would be to check the number of milliseconds
// past since the last draw call and update the animation’s position based on the time difference
var time;
var draw = function() {
requestAnimationFrame(draw);
var now = new Date().getTime(),
dt = now - (time || now);
time = now;
// Drawing code goes here... for example updating an 'x' position:
this.x += 10 * dt; // Increase 'x' by 10 units per millisecond
};
@molokoloco
Copy link
Author

var fadeIn = function (el) {
        var fade = 0;
        el.style.opacity = fade;
        var tick = function() {
            fade += 0.05;
            el.style.opacity = fade;
            if (fade >= 1) el.style.opacity = 1;
            else setTimeout(tick, 1000/25);
        };
        tick();
};

var myBody = document.body;
fadeIn(myBody);

function smoothIn(el) {
    el.style.opacity = 0;
    var last = new Date().getTime();
    var tick = function() {
      var current = new Date().getTime();
      el.style.opacity += (current - last) / 400;
      last = current;
      if (el.style.opacity < 1)
        (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }
    tick();
}

smoothIn(el);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment