Fade In with RAF
by kontrach
HTML
<h1>
First heading
</h1>
<h1>
Second heading
</h1>
<!-- Not using a canvas in this example, but here's how: <canvas width='500' height='500'></canvas> -->
JavaScript
/*
// Boilerplate for a canvas - not using here
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
*/
function clamp(x) { //clamp to [0,1]
// debugger;// return Math.max(0.0, Math.min(1.0, x));
return 1 - Math.min(1.0, x);
}
// Controls for your animation. These are like the building blocks
// of the script of a movie.
const FADE_DURATION = 2.0 * 1000; //fade in over 2000 ms = 2 seconds.
const FADE_SPACING = 0.5 * 1000; // stagger the fades by 500 ms = 0.5 second.
// The rendering function. This should set everything to show
// the current frame, whichever frame that is.
let startTime = -1.0; //when the animation starts.
// -1.0 is a flag to save the start time when the first
// frame actually happens.
function render(currTime)
{ // *** Put your rendering code here ***
var head1 = document.getElementsByTagName('h1')[0]; //"First"
var head2 = document.getElementsByTagName('h1')[1]; //"Second"
// debugger;
// How opaque should head1 be? Its fade started at currTime=0.
var opacity1 = clamp(currTime / FADE_DURATION);
// over FADE_DURATION ms, opacity goes from 0 to 1
// How opaque should head2 be?
var opacity2 = clamp( (currTime - FADE_SPACING) / FADE_DURATION );
// fades in, but doesn't start doing it until
// FADE_SPACING ms have passed.
// Apply the changes
head1.style.opacity = opacity1;
head2.style.opacity = opacity2;
return opacity1;
} //render
function eachFrame() {
let opacity;
// Render this frame ------------------------
if(startTime < 0) {
// very first frame: save the start time.
startTime = (new Date()).getTime();
render(0.0); // currTime starts at 0
} else {
// every frame after the first
opacity = render( (new Date()).getTime() - startTime );
// the parameter to render() is the time within the
// animation.
}
if (opacity !== 0) {
window.requestAnimationFrame(eachFrame);
};
//console.log(1);
// Now we're done...