Mike
Mike

Reputation: 159

PIXI getting image width,height

I need to get size of image that I just added to stage and set it to defaultX and defaultY before I call the autorenderer, but I can't seem to grab the size. How do I grab the size? Also, from what I got so far, I think the best way to set the size is including with autorenderer. But what would be the implication here if I resize() later? Any help will be appreciated. Thank you.

my code:

this.stage = new PIXI.Container();
var texture = PIXI.Texture.fromImage('background.png'); //1610x640
var spr = new PIXI.Sprite(texture);
this.stage.addChild(spr);

defaultX = texture.width;
defaultY = texture.height;

this.renderer = PIXI.autoDetectRenderer(defaultX, defaultY); //640x690

this.renderer.resize(x,y); // I know this works with other values 
                           // eg if I hardcode with 1610,640
                           // but texture.width doesn't work and
                           // I don't want to hardcode it

Upvotes: 0

Views: 6584

Answers (1)

Alexandr Curtov
Alexandr Curtov

Reputation: 11

Your image can not be loaded when you call texture.width.

I use next construction:

this.stage = new PIXI.Container();
this.renderer = PIXI.autoDetectRenderer(640, 690); //640x690

var baseTexture = new PIXI.BaseTexture('background.png');

// can be loaded from cache
if (baseTexture .hasLoaded) {
    createSprite(baseTexture);
} else {       
    baseTexture .on('loaded', function() {
        createSprite(baseTexture); // or this
    });
}

function createSprite(baseTexture) {
    var texture = new PIXI.Texture(baseTexture);
    var spr = new PIXI.Sprite(texture);
    this.stage.addChild(spr);

    defaultX = texture.width;
    defaultY = texture.height;

    this.renderer.resize(defaultX,defaultY);
}

Upvotes: 1

Related Questions