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!
/**
* 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 = 0;
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, 2) + Math.pow(originY - this.y, 2));
};
/**
* 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 the...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.