Brady Zhu
Brady Zhu

Reputation: 1405

Chrome cannot get the width and height from an image created by JavaScript

My web application has many image presentation features, and most of time we need to resize them. I attempted to get its real width and height values by the following fragment code:

var image = new Image();
image.src = IMAGE_URL;

var width = image.width;
var height = image.height;

The above code runs no problem on browsers like Firefox and IE 10, but it returns 0 on Chrome. I guess Chrome doesn't support this.

Can anybody gives me guidance on this?

Upvotes: 1

Views: 2546

Answers (3)

geevee
geevee

Reputation: 5451

you need to get width and height after the image loads and understands what its made of.

try:

var image = new Image();
image.onload = function() {
    var width = image.width;
    var height = image.height;
}
image.src = IMAGE_URL;

hope that helps

Upvotes: 4

Prateek
Prateek

Reputation: 6965

Try this

img = new Image();
img.onload = function() {
    width = this.width;
    height = this.height;
};

Onload help you to get width and height.

Upvotes: 2

alex
alex

Reputation: 490163

You need to wait for the load event, otherwise the dimensions of the image won't be known.

var image = new Image();

image.onload = function() {
    var width = image.width;
    var height = image.height;
    // These values will now be correct.
};

image.src = IMAGE_URL;

Upvotes: 1

Related Questions