Jordan Hensley
Jordan Hensley

Reputation: 440

How do I get the width and height of an image stored inside a javascript object?

I am looking of a way to find the dimensions of the passed in image. When I log the height and width it returns 0 for both.

function GamePiece(imageName){
    this.image = new Image();
    this.image.src = imageName;
    this.width = this.image.width;
    this.height = this.image.height;
}

Upvotes: 0

Views: 24

Answers (1)

Wayne Allen
Wayne Allen

Reputation: 1745

You need to allow the browser time to load the image before you can get it's size. You can use the onload callback to detect when the image is loaded.

function GamePiece(imageName){
    var gamePiece = this;

    this.image = new Image();
    this.image.onload = function() {
        gamePiece.width = this.width;
        gamePiece.height = this.height;
    }
    this.image.src = imageName;
}

There will be a delay before the callback is run and the dimensions are set on your object.

Upvotes: 1

Related Questions