c3d2-web/content/static/datenspuren/script/clouds.js

86 lines
2.3 KiB
JavaScript

/* http://paulirish.com/2011/requestanimationframe-for-smart-animating/ */
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 20);
};
})();
function Flash(x, y) {
this.el = $('<img class="backgroundflash" src="images/flash.png"/>');
this.el.css('left', (x-10)+'px');
this.el.css('top', y+'px');
$('body').append(this.el);
var that = this;
this.el.fadeOut(250, function() {
that.el.detach();
});
}
function Cloud() {
this.lastUpdate = new Date().getTime();
this.speedX = Math.random() * 200;
if (Math.random() < 0.5) {
this.x = -50;
} else {
this.speedX *= -1;
this.x = $('body').innerWidth();
}
this.y = Math.floor(Math.random() * $('body').innerHeight());
this.el = $('<img class="backgroundcloud" src="images/pixelcloud.png"/>');
$('body').append(this.el);
}
Cloud.prototype.update = function() {
var now = new Date().getTime();
this.x += this.speedX * (now - this.lastUpdate) / 1000;
this.lastUpdate = now;
this.el.css('left', Math.floor(this.x) + 'px');
this.el.css('top', this.y + 'px');
if (this.isDone())
this.el.detach();
};
Cloud.prototype.isDone = function() {
return (this.x < -100) || (this.x > $('body').innerWidth());
};
var clouds = [];
function stepClouds() {
if (clouds.length < 23 && Math.random() < 0.1)
clouds.push(new Cloud());
clouds = clouds.filter(function(cloud) {
cloud.update();
return !cloud.isDone();
});
clouds.forEach(function(cloud1) {
clouds.forEach(function(cloud2) {
if (cloud1 !== cloud2 &&
cloud1.x > cloud2.x - 40 &&
cloud1.x < cloud2.x + 40 &&
cloud1.y > cloud2.y - 72 &&
cloud1.y < cloud2.y + 72 &&
Math.random() < 0.01)
new Flash(Math.floor((cloud1.x + cloud2.x) / 2),
Math.max(cloud1.y, cloud2.y) + 40);
});
});
requestAnimFrame(stepClouds, 'body');
}
$(document).ready(function() {
setTimeout(stepClouds, 100);
});