javascript - Displaying multiple Thumbnails not working -
so making "drop-zone" website.
the user can drag , drop images on area , jpegs dropped on area displayed thumbnailes. made list of jpegs dropped on area , working fine. everytime new jpeg added list want display jpegs thumbnailes of size 100x150px.
here code that. , here fiddle http://jsfiddle.net/cjkyj/2/
function displaythumbnailes( ) { //clear div. var outerdiv = document.getelementbyid('filechooserdiv'); while (outerdiv.haschildnodes()) { outerdiv.removechild(outerdiv.lastchild); } var div = document.createelement('div'); outerdiv.appendchild(div); //go on files , add thumbnails jpegs. for( var = 0; < files.size(); i++) { if( files.get(i).type == "image/jpeg") { var reader = new filereader(); reader.onloadend = function() { var result = reader.result; displaythumbnail( result, div ); } reader.readasdataurl(files.get(i)); } } } function displaythumbnail( src, div ) { var img = new image(); img.onload = function () { var cv = document.createelement('canvas'); cv.style.border = "1px solid #ffffff"; cv.width = 100; cv.height = 150; var ctx = cv.getcontext( "2d" ); ctx.drawimage(img, 0, 0, 100, 150); div.appendchild(cv); } img.src = src; }
my problem: believe code display thumbnailes in area of div see last one.
this looks messing synchronisation or something. "files" object manages files dragged on "drop-zone". want every thumbnail have own canvas can add onclick event them later.
any appriciated ^^
your code:
reader.onloadend = function() { var result = reader.result; displaythumbnail( result, div ); } reader.readasdataurl(files.get(i));
was failing because of async onloadend callback. each pass through loop updated outer reader
variable, each event used last reference.
you either change code wrap in closure:
(function(reader) { reader.onloadend = function() { var result = reader.result; displaythumbnail( result, div ); }})(reader);
or (preferred) change code use event specific data :
reader.onloadend = function(evt) { var result = evt.target.result; displaythumbnail( result, div ); };
-- or using onload --
reader.onload = function (evt) { var result = evt.target.result; displaythumbnail(result, div); } reader.readasdataurl(files.get(i));
works: example
i should note rearranged code run within onload
handler.
Comments
Post a Comment