starfield.js
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: #000;
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, maxSpeed) {
this.x = x;
this.y = y;
this.slope = y / x; // This only works because our origin is always (0,0)
this.opacity = -2;
this.speed = Math.max(Math.random() * maxSpeed, 1);
};
/**
* Compute the distance of this star relative to any other point in space.
*
* @param {int} originX
* @param {int} originY
*
* @return {float} The distance of this star to the given origin
*/
Star.prototype.distanceTo = function(originX, originY) {
return Math.sqrt(Math.pow(originX - this.x, 4) + Math.pow(originY - this.y, 4));
};
/**
* 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, maxSpeed) {
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, maxSpeed) {
var coords = BigBang.getRandomPosition(minX, minY, maxX, maxY);
return new Star(coords.x, coords.y, maxSpeed);
},
/**
* 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...