starfield

drawn random dots of varying brightness on a black background

by rob Davis

HTML

<div id="container">
    <canvas id="starfield" />
</div>

CSS

#container { background-color:yellow;
        width:500px;
    height:500px;
}

JavaScript

var canvas = document.getElementById('starfield');
var context = canvas.getContext('2d');
var width=250;
var height=250;

var maxStars=1000;
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);

context.fillStyle = "#000";
context.fillRect(0,0,canvas.width, canvas.height);

for (var i=0;i<maxStars;i++) {
    drawDot(context, getRandomRange(0,canvas.width), getRandomRange(0,canvas.height), getRandomRange(1,4), 'rgba('+Math.round(getRandomRange(180,255))+','+Math.round(getRandomRange(200,255))+','+Math.round(getRandomRange(200,255))+','+ getRandom()+')');
}

function drawDot(context, x, y, size, style) {
    var mark = size/2;
    context.save();
    context.translate(x,y);
    context.fillStyle=style;
    context.fillRect(0-mark,0-mark,mark, mark);
    context.restore();
}

// return random value between 0 and 1.0
function getRandom() {
    return Math.random();
}

// return random float value between min and max (including min and up to but not including the whole number max)
function getRandomRange(min,max) {
    return min + ( max * getRandom());
}