Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.
Notice: I'm taking a break from blogging to focus on Atari Gamer . com, check it out!

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
I've been playing around with star field generation quite a bit lately for my game, so I've made a jsFiddle to test it out.

Here's a result of what it can produce:

The jsFiddle is here: http://jsfiddle.net/TBMTT/

I'm using EaselJS as the HTML5 drawing library, although for the star field, the drawing can be achieved using the standard HTML5 canvas methods.

Below is the code used to generate the star field. It will generate 1500 stars with various sizes and colours.Most of the stars will be 'small', however there is a chance to get a 'big' star. This chance is quite low to make the field look more realistic. The colours are also chosen at random for all star sizes.
backgroundStage = new createjs.Stage("backgroundCanvas");
var stars = 1500;
var starField = new createjs.Shape();
var canvasWidth = 640;
var canvasHeight = 480;
var starSmallRadiusMin = 1;
var starSmallRadiusVarience = 2;
var starBigRadiusMin = 3;
var starBigRadiusVarience = 6;
var starBigChance = 0.025;
for (var i = 0; i < stars; i++) {
var mX = Math.floor(Math.random() * canvasWidth);
var mY = Math.floor(Math.random() * canvasHeight);
var bigStar = Math.random();
var radius;
if (bigStar < starBigChance) {
radius = starBigRadiusMin + (Math.random() * starBigRadiusVarience)
else {
radius = starSmallRadiusMin + (Math.random() * starSmallRadiusVarience);
var colour, colourType = Math.round(Math.random() * 5);
switch (colourType) {
case 0: colour = "#558"; break;
case 1: colour = "#fff"; break;
case 2: colour = "#aaa"; break;
case 3: colour = "#888"; break;
case 4: colour = "#855"; break;
case 5: colour = "#585"; break;
Math.random() * canvasWidth,
Math.random() * canvasHeight,
5 + Math.round(Math.random() * 2), // number of sides
0.9, // pointyness
Math.random() * 360 // rotation of the star


Skip down to comments...
A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. If you spot something out of place, please do let me know.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...