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

3.4k Views Asked by At

I'm working on an app that is dynamically generating images with Javascript's image() object. Code below, where object is the URL I am passing in -

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;
    },

The output of my console log shows the image object is created with source set to URL -
<img src="https://z3nburmaglot.zendesk.com/attachments/token/F0Y7C9UfUcOaA7nCMJfE5T1yB/?name=Show+Support+Tickets+on+Customer+View.png"> and height and width of 0.

Some of the images load fine - they set height and widgth appropriately and if I refresh the JS (run the function again), the images that had 0 height and width suddenly change to the correct height and width.

Any thoughts on why constructing an image this way would fail sometimes?

1

There are 1 best solutions below

5
On BEST ANSWER

Sounds like your image hasn't loaded yet when you get its width or height. Then it will be 0.

When you refresh, the image is in your browser cache and will load immediately so its width and height are available straight up.

Use the onload() event of the Image object to execute code once the image has been loaded properly

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;
},