starfield.js (mrdoob ed.)
Mr. Doob shared his oldskool graphics knowledge to build a much better looking starfield!
http://www.twitter.com/mrdoob
Recreate the infamous Windows 3.1 screensaver "Starfield" using raw JS and canvas.
Done during #Freakend12 to test drawing some dumb stuff in canvas2d.
now with 200% more requestAnimationFrame!
HTML
<div class="fullScreen" id="fullScreen">
<canvas id="canvas2d"></canvas>
</div>
CSS
html, body {
overflow: hidden;
background: #150025;
padding: 0px; margin: 0px;
width: 100%; height: 100%;
}
.fullScreen {
height: 100%;
}
JavaScript
/**
* The stars in our starfield!
* Stars coordinate system is relative to the CENTER of the canvas
* @param {number} x
* @param {number} y
*/
var Star = function(x, y) {
this.x = x;
this.y = y;
this.z = Math.random() * 200; // Fake!
};
/**
* Reinitializes this star's attributes, without re-creating it
*
* @param {number} x
* @param {number} y
*
* @return {Star} this star
*/
Star.prototype.resetPosition = function(x, y) {
Star.apply(this, arguments);
return this;
};
/**
* The BigBang factory creates stars (Should be called StarFactory, but that is
* a WAY LESS COOL NAME!
* @type {Object}
*/
var BigBang = {
/**
* Returns a random star within a region of the space.
*
* @param {number} minX minimum X coordinate of the region
* @param {number} minY minimum Y coordinate of the region
* @param {number} maxX maximum X coordinate of the region
* @param {number} maxY maximum Y coordinate of the region
*
* @return {Star} The random star
*/
getRandomStar: function(minX, minY, maxX, maxY) {
var coords = BigBang.getRandomPosition(minX, minY, maxX, maxY);
return new Star(coords.x, coords.y);
},
/**
* Gets a random (x,y) position within a bounding box
*
*
* @param {number} minX minimum X coordinate of the region
* @param {number} minY minimum Y coordinate of the region
* @param {number} maxX maximum X coordinate of the region
* @param {number} maxY maximum Y coordinate of the region
*
* @return {Object} An object with random {x, y} positions
*/
getRandomPosition: function(minX, minY, maxX, maxY) {
return {
x: Math.floor((Math.random() * maxX) + minX),
y: Math.floor((Math.random() * maxY) + minY)
};
}
};
/**
* Constructor function of our starfield. This just prepares the DOM nodes where
* the scene will be rendered.
*
* @param {string}...