FileReader+canvas image loading problem

故事扮演 提交于 2019-12-12 17:11:31

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/6004011/filereadercanvas-image-loading-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!