FileReader + canvas图片加载问题 [英] FileReader+canvas image loading problem
问题描述
我正在使用此代码在客户端浏览器上加载一些图片:
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);
}
但在reader.onload函数中有问题, img.width属性。仍然设置为零。这种行为在chrome也是,所以它可能是我的错。
你能说我,问题在哪里?
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?
谢谢你,JV
推荐答案
我还没有使用FileReader对象,但是,据我所知,问题是以下:给你分配一个值 img.src
图片不立即可用。它必须首先加载 - 至少这是如何使用远程文件。 img元素将在图像加载完成后触发onload事件。我假设如果你分配一个数据url也是如此。你应该听这个事件,并从那里调用你的createImgCanvas。
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.
这篇关于FileReader + canvas图片加载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!