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

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...
Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...