Javascript Image() 对象有时错误地将高度和宽度设置为 0

Javascript Image() object erroneously setting height and width to 0 sometimes

我正在开发一个使用 Javascript 的 image() 对象动态生成图像的应用程序。下面的代码,其中对象是我传入的 URL -

resizeImage: function(object) {
        var img = new Image();
        img.src = object;
        console.log(img);
        console.log(img.width);
        console.log(img.height);
        var ratio;
        if(img.width > img.height) {
            ratio = 82/img.width;
        } else {
            ratio = 82/img.height;
        }
        img.height *= ratio;
        img.width *= ratio;
        return img;
    },

我的控制台日志的输出显示图像对象是在源设置为 URL -
的情况下创建的 <img src="https://z3nburmaglot.zendesk.com/attachments/token/F0Y7C9UfUcOaA7nCMJfE5T1yB/?name=Show+Support+Tickets+on+Customer+View.png"> 和高度和宽度为 0.

一些图像加载正常 - 它们适当地设置了高度和宽度,如果我刷新 JS(运行 函数再次),高度和宽度为 0 的图像突然变为正确的高度和宽度。

有没有想过为什么用这种方式构建图像有时会失败?

当您获取图像的宽度或高度时,听起来您的图像尚未加载。那么它将是0.

当您刷新时,图像会在您的浏览器缓存中并会立即加载,因此它的宽度和高度直接可用。

图像正确加载后,使用 Image 对象的 onload() 事件执行代码

resizeImage: function(object) {
    var img = new Image();

    // first set onload event
    img.onload = function() {
        console.log(img);
        console.log(img.width);
        console.log(img.height);
        var ratio;
        if(img.width > img.height) {
            ratio = 82/img.width;
        } else {
            ratio = 82/img.height;
        }
        img.height *= ratio;
        img.width *= ratio;
    }

    // then set the src
    img.src = object;

    return img;
},