Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

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:
starfieldjs.png


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;
}
starField.graphics.beginFill(colour)
.drawPolyStar(
Math.random() * canvasWidth,
Math.random() * canvasHeight,
radius,
5 + Math.round(Math.random() * 2), // number of sides
0.9, // pointyness
Math.random() * 360 // rotation of the star
);
}
backgroundStage.addChild(starField);
backgroundStage.update();


-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

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.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.