I am traing to load some images on client browser with this code:
function addFiles()
var input = document.querySelector("input[type='file']");
var files = input.files;
var previewEl = document.getElementById("preview");
for (var i = 0; i < files.length; i++) {
if (!files[i].type.match(/image.*/)) {
alert("This is not image!");
continue;
};
var divEnvelop = document.createElement('div');
divEnvelop.setAttribute('class','imgPrevEnvelop');
开发者_开发技巧 divEnvelop.setAttribute('id',"img"+i);
previewEl.appendChild(divEnvelop);
var img = document.createElement("img");
img.file = files[i];
var reader = new FileReader();
reader.onload = (function(aImg, aName, aEnvelop) { return function(e) {
aImg.src = e.target.result;
//here I don't have img.width - problem
createImgCanvas(aImg, aImg.width, aImg.height, 300, 300, aName, aEnvelop);
}; })(img,files[i].name, divEnvelop);
reader.readAsDataURL(files[i]);
}
}
function createImgCanvas(img, imgWidth, imgHeight, width, height, label, divEnvelop) {
if (imgWidth > imgHeight) {
if (imgWidth > width) {
imgHeight *= width / imgWidth;
imgWidth = width;
}
} else {
if (imgHeight > height) {
imgWidth *= height / imgHeight;
imgHeight = height;
}
}
var canvas = document.createElement('canvas');
canvas.setAttribute('id',label);
canvas.width = imgWidth;
canvas.height = imgHeight;
var imageCanvas2D = canvas.getContext("2d");
try{
imageCanvas2D.drawImage(img, 0, 0, imgWidth, imgHeight);
} catch(err) { alert(err);}
divEnvelop.appendChild(canvas);
}
but there is problem in reader.onload function, wher I don't have img.width property. Is still set to zero. This behaviour is in chrome too, so it will be probably my fault. Could you say me, where is the problem please?
Thanks, JV
I haven't worked with the FileReader object yet, however, as far as I can tell, the problem is the following: After you assigned a value to img.src
the image is not instantly available. It has to be loaded first - at least that is how it is if you work with remote files. The img element will fire an onload event, as soon as the image is done loading. I assume this is also true if you assign a data url. You should listen for this event and call your createImgCanvas from there.
精彩评论