Edit in JSFiddle

var canvasWidth = 512;
var canvasHeight = 512;
var canvasBackgroundColor = { r:0, g:0, b:0, a:255 };

//---

var rectangles = 100;
var rectangleHolder = [];
    
function createRandomRects() {

	for ( var i = 0; i < rectangles; i++ ) {
  	
    var rect = {};
        rect.width  = Math.round( Math.random() * ( canvasWidth / 2 ) ) + 10;
        rect.height = Math.round( Math.random() * ( canvasHeight / 2 ) ) + 10;
        rect.x = Math.ceil( Math.random() * ( canvasWidth - rect.width ) );
        rect.y = Math.ceil( Math.random() * ( canvasHeight - rect.height ) );
        rect.color =  { r:Math.floor( Math.random() * 255 ), g:Math.floor( Math.random() * 255 ), b:Math.floor( Math.random() * 255 ), a:255 };
        
		rectangleHolder.push( rect );
  
  }

};    
    
createRandomRects();  
   
//---

var canvas = document.createElement( 'canvas' );
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
	
document.body.appendChild( canvas );

var context = canvas.getContext( '2d' );
var imageData = context.getImageData( 0, 0, canvasWidth, canvasHeight );
var data = imageData.data;

//---

function fillRect( i, ix, iy, x, y, width, height, color ) {

	var between = function( value, min, max ) {
  
    return value >= min && value <= max;

  };	

  if ( between( ix, x, x + width - 1 ) && between( iy, y, y + height - 1 ) ) {

    data[ i ]     = color.r;
    data[ i + 1 ] = color.g;
    data[ i + 2 ] = color.b;
    data[ i + 3 ] = color.a;

  }

};

for ( var i = 0, l = data.length; i < l; i += 4 ) {

  data[ i ]     = canvasBackgroundColor.r;
  data[ i + 1 ] = canvasBackgroundColor.g;
  data[ i + 2 ] = canvasBackgroundColor.b;
  data[ i + 3 ] = canvasBackgroundColor.a;
  
  var ix = ( i / 4 ) % canvasWidth;
  var iy = Math.floor( ( i / 4 ) / canvasWidth );
  
  for ( var j = 0, m = rectangleHolder.length; j < m; j++ ) {
  
  	var rect = rectangleHolder[ j ];
    
    fillRect( i, ix, iy, rect.x, rect.y, rect.width, rect.height, rect.color );
  
  }

}

context.putImageData( imageData, 0, 0 );