Image transition (RequestAnimationFrame) (2/3)
Animated transition between images using requestAnimationFrame. This uses less CPU and lets you mess up with animation timing.
by Karl Tayfer
HTML
<div id="box">
<img id="logo" src="http://www.google.com/logos/1999/googlepump.gif" alt="Google Doodle" />
</div>
CSS
#box {
background:#000;
text-align:center
}
JavaScript
/*
* Image transition (RequestAnimationFrame) (2/3)
* More at http://jsfiddle.net/user/daPhyre/
*/
window.addEventListener('load', load, false);
var logo = null,
lastUpdate = 0,
time = 1,
currentImage = 0,
images = [
'http://www.google.com/logos/1999/googlepump.gif',
'http://www.google.com/logos/1999/turkey_home2.gif',
'http://www.google.com/logos/1999/snowmanC.gif'];
function load(evt) {
logo = document.getElementById('logo');
run();
}
function run() {
requestAnimationFrame(run);
var now = Date.now();
var deltaTime = (now - lastUpdate) / 1000;
if (deltaTime > 1) deltaTime = 0;
lastUpdate = now;
act(deltaTime);
}
function act(deltaTime) {
time += deltaTime;
if (time < 1) {
logo.style.opacity = time;
} else if (time > 4) {
if (time < 5) {
logo.style.opacity = 5 - time;
} else {
currentImage++;
if (currentImage >= images.length) {
currentImage = 0;
}
logo.src = images[currentImage];
time -= 5;
}
}
}