Canvas Snow
Another snowfall example, inspired by the many blizzards which have hit Maine recently. Also making use of the Visibility API, because IE<=9 can go to hell.
by Brian Cribb
HTML
<div id="canvasContainer"></div>
<p>Using the Visibility API to make sure this pauses when the tab isn't visible. Without this, the snowflakes would end up all screwy if you went to another tab for a few moments. To see this, disable the event listener for <code>visibilityChange</code>.</p>
<p>Also, you'll notice that I'm not really using <code>cancelAnimationFrame</code> anymore. This is kind of a new thing, and doesn't work everywhere yet. Instead, I'm used the tried-and-true method of having a pause variable. If that's <code>true</code> then the update is never run for the animations or the timer.</p>
CSS
p {
max-width:600px;
}
canvas, p {
display:block;
margin: 0 auto;
}
canvas {
background:#183794;
margin-bottom:10px;
}
JavaScript
/*
INSPIRATIONS:
Structure inspired by:
http://viget.com/extend/2666
Page Visibility API and Polyfill for vendor prefixes:
http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active
http://www.w3.org/TR/page-visibility/
http://caniuse.com/#feat=pagevisibility
http://jsfiddle.net/0GiS0/cAG5N/
Each flake has its own personal resistance to wind and gravity, giving their own speed and a feeling of randomness
to the way they fall. Bigger flakes move faster to give the illusion that they're closer, even though there's no
third dimension here. Future improvements would include spacing out the initial placement of the snowflakes to make
sure they don't accidentally start in the same spot. (Not likely, but possible with random placement.)
*/
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var APP = {
props: {
width:600, // Width of our canvas app. Used when creating the canvas and testing its bounds.
height:300, // Height of our canvas app.
keycodes: {
SPACE: 32,
LEFT: 37,
RIGHT: 39,
UP: 38,
DOWN: 40
},
paused: false,
textColor: '#FFFD8A',
frameNum:0,
avgFPS:0,
gravity:80,
wind:15
},
pause: function() {
console.log('APP.pause()');
window.cancelAnimationFrame(APP.core.animationFrame);
APP.props.paused = true;
},
play: function() {
console.log('APP.play()');
APP.core.then = Date.now();
APP.props.paused = false;
APP.core.frame();
},
init: function() {
// Setting strings to match vendor visibility names.
if (typeof document.hidden !== "undefined") {
APP.hidden = "hidden", APP.visibilityChange = "visibilitychange", APP.visibilityState = "visibilityState";
} else...