Edit in JSFiddle

var w = 600;
var h = 600;

//---

var canvas = document.createElement( 'canvas' );
	canvas.width = w;
	canvas.height = h;
	
document.body.appendChild( canvas );

var context = canvas.getContext( '2d' );
	context.fillStyle = '#000000';
	context.fillRect( 0, 0, w, h );
  
var cubes = Math.ceil( Math.random() * 150 ) + 50;
var cubeWidth = 15;
var cubeHeight = 15;
var cubeDistanceX = 1;
var cubeDistanceY = 1;
var cubesInARow = 9;

for ( var i = 0; i < cubes; i++ ) {

	var x = i % cubesInARow;
  var y = Math.floor( i / cubesInARow );

  context.fillStyle = '#FF0000';
  context.fillRect( x * ( cubeWidth + cubeDistanceX ), y * ( cubeHeight + cubeDistanceY ), cubeWidth, cubeHeight ); 

}