javascript图像onload的宽度为0,高度为0

javascript image onload has 0 width and 0 height

本文关键字:高度 图像 onload javascript      更新时间:2023-09-26

我正在从文件系统加载一个图像,然后我想调整图像的大小。它在除IE(11)之外的所有浏览器中都能正常工作。问题是图像已加载,但宽度和高度为0。

我没有选择,所以我在这里发布这个问题。

这是代码

function getAsImage(readFile, chatboxtitle) {
    var reader = new FileReader();
    reader.readAsDataURL(readFile);
    reader.onload = addImg;
}
function addImg(imgsrc) {
    var img = document.createElement('img');
    img.setAttribute("src", imgsrc.target.result);
    console.log(img);
    console.log(img.width + " "+img.height);
    ... a lot of cool stuff happens here but it doesn't work because width is 0
}

好的,控制台会打印出类似的图像

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAH0CAYAAAHUIW ... and much more.. >

所以图像就在那里。除IE外,所有浏览器都能正常工作。

我试着设置一些IMG属性,比如样式、宽度,但都不起作用。

注意,我不是一个铁杆JavaScript开发人员。也许我错过了什么。是否找不到DOM元素?

更新

我昨天试了一下下面的答案,结果是有效的。但我今天尝试了这个解决方案,但它已经不起作用了。试试这把小提琴。它在Windows7上的IE11中不起作用,但在Windows8上的IE11中起作用。

怪异的IE行为。事实证明,您需要使用设置src

img.src = src_goes_here

不通过setAttribute

(function(doc){
    doc.getElementById('file').addEventListener('change', readFile);
    function readFile(ev) {
        var file = this.files[0],
            reader;
        if(file) {
            reader = new FileReader();
            reader.onload = getSize
            reader.readAsDataURL(file);
        }
    }
    function getSize(ev) {
        var img = doc.createElement('IMG');
        img.src = this.result; //wors in IE11
        //img.setAttribute('src', this.result); //doesn't work
        console.log(img.width, img.height);
    }
}(document))

演示。

UPD:一些额外的研究表明,当您使用img.setAttribute设置src时,为了使IE计算图像大小,您需要将图像实际附加到文档中。例如

document.body.appendChild(img);

另一个演示。