var images = []; var positions = [[0,0]]; var canvas = document.querySelector('#wall'); var context = canvas.getContext('2d'); var max_preload = 10; current_load = 0; var total_images = 10000; var current_images = 0; var max_img_size = 20; var min_img_size = 30; function load_image(){ if( current_load >= max_preload || current_images >= total_images){ return; } var im = new Image(); im.src = "http://sandropaganotti.com/wp-content/goodies/misc/smarties.jpg?" + Math.random(); current_images ++; current_load ++; im.onload = function(ev){ current_load --; images.push(ev.target); } } function draw_image(){ if(images.length == 0){ return; } var im = images.pop(); img_width = im.width; img_height = im.height; img_size = img_width > img_height ? img_width : img_height; canvas_img_size = img_size > max_img_size ? max_img_size : img_size; if(img_width > img_height){ canvas_img_width = canvas_img_size; canvas_img_height = Math.round(( canvas_img_size * img_height ) / img_width); }else{ canvas_img_width = Math.round(( canvas_img_size * img_width ) / img_height); } var candidate = [0,0] while(positions.length > 0){ candidate = positions.shift(); if (candidate[0] + canvas_img_width < canvas.width && candidate[1] + canvas_img_height < canvas.height){ break; } } var start_pos_x = candidate[0]; var start_pos_y = candidate[1]; context.drawImage(im, start_pos_x, start_pos_y,canvas_img_width, canvas_img_height); positions.push([start_pos_x + canvas_img_width, start_pos_y],[start_pos_x, start_pos_y + canvas_img_height]); positions = _.uniq(_.sortBy(positions, function(pos){ return pos[0]+pos[1]; }), true, function(pos){ return ""+pos[0]+","+pos[1]+"";}); } setInterval(load_image, 100); setInterval(draw_image, 100);