Jump to content

Load textures synchronously


u5bob
 Share

Recommended Posts

Is there anyway to load textures in pixi synchronously? Something like:

var texture = PIXI.Texture.fromImage("bunny.png", onComplete);function onComplete() {   var bunny = new PIXI.Sprite(texture);}

I tried the following:

var img = new Image();img.onload = onComplete;img.src = 'bunny.png';function onComplete() {  var texture = new PIXI.Texture(new PIXI.BaseTexture(img));}

But the code above gives me an error.

 

 

Please let me know how I can make pixi work synchronously. Thank you in advance.

 

EDIT:

 

I also tried: http://jsfiddle.net/8MawM/

but, it also gives me an error.

Link to comment
Share on other sites

Have you tried Pixi's built-in ImageLoader?

var loader = new PIXI.ImageLoader("images/anyImage.png");loader.onLoaded = makeSprites.bind(this);loader.load();function makeSprites() {  var texture = PIXI.TextureCache["images/anyImage.png"];  var sprite = new PIXI.Sprite(texture);}
Link to comment
Share on other sites

Yup! 

 

D13 is right you could chain the loading of the assets and treat onLoaded as a form of callback that would iterate over the images. Put them into array and make a dynamic reference! Should work swell! :D

 

This is a sample of my loader class.

_li.define(    'multiverse.assets.addAssets',    function (initialize, views, core) {        'use strict';        var init,            addAssets,            loaded;                init = function (data) {                        loaded = false;            var loader = new PIXI.AssetLoader(data.assets, false);            loader.addEventListener('onProgress', function(e){                                var percent = 1 - (e.content.loadCount / e.content.assetURLs.length);                var data = e.content.loadCount;                                if(percent !== 1){                                    }            });                        loader.onComplete = function(){                                core(data.callback);                            };                        loader.load();                        return addAssets;                    };        return init;    },    [        'multiverse.assets', 'multiverse.views', 'multiverse.core'    ]);
Link to comment
Share on other sites

hmm.. synchronously implies thread execution would 'stop' until that operation completed.. like assigning a value to a variable. The next line within the scope of that function doesn't execute until that assignment is performed. 

I suspect you don't really care (or require) whether the nature of the connection itself is synchronize or asynchronous. You just want the callback function fired off when the load is completed.

I don't know exactly what error your getting, but I see you're passing 'texture' (which is undefined) into PIXI.sprite in the first code segment you supplied. . try passing 'this' instead.. also, the 'onComplete' function will likely be called with event arguments.. you don't seem to require them, but it's a good idea to account for them. I usually use 'e'.. but for this example I'm going to write 'eventArg'

var texture = PIXI.Texture.fromImage("bunny.png", onComplete);function onComplete(eventArg) {   var bunny = new PIXI.Sprite(this);}/* Note: this function won't actually work, because fromImage doesn't dispatch an event, nor does it process delegates passed to it*/

in the second code segment you're passing img (which is undefined) into a new instance of PIXI.BaseTexture.. try passing 'this' instead

var img = new Image();img.onload = onComplete;img.src = 'bunny.png';function onComplete(eventArg) {  var texture = new PIXI.Texture(new PIXI.BaseTexture(this.src));}/* this callback function will fire.However, PIXI.BaseTexture does not use an Image type for its constructor.. it uses a string to the ImageUrl. Thus you would be constructing an image needlessly.. which in turn makes the callback function onload pointless, right? */

also.. note that 'onComplete' is not a good function name as it might cause a conflict.. so onLoadTextureComplete would be more suitable.. though, there are naming conventions for this sort of thing.. of which I'm not utmost familiar with in Javascript :P

EDIT: included the eventArg sentiment.

EDIT: I didn't check the documents when I posted this..neither of the methods supplied work properly.. 

Edited by mrBRC
Link to comment
Share on other sites

I've updated your jsFiddle: http://jsfiddle.net/8MawM/4/

An obvious issue with the fiddle you provided was that you didn't have an 'External Resource' reference to a pixi.js added. Perhaps that was an overlook... 

 

var stage = new PIXI.Stage(0xF2F2F2); var renderer = PIXI.autoDetectRenderer(400, 300); document.body.appendChild(renderer.view);var imageLoader = new PIXI.ImageLoader("http://www.goodboydigital.com/pixijs/logo_small.png", true);imageLoader.addEventListener("loaded", onComplete);imageLoader.load();renderer.render(stage);function onComplete(e) {    console.log("event data: ", e);    var bunny = new PIXI.Sprite(e.content.texture);        bunny.position = new PIXI.Point(200,150);    stage.addChild(bunny);     renderer.render(stage);}

this is the modified jsFiddle content... 

Pixi Documentation Reference:

ImageLoader: http://www.goodboydigital.com/pixijs/docs/files/src_pixi_loaders_ImageLoader.js.html#l39 

EventTarget: http://www.goodboydigital.com/pixijs/docs/files/src_pixi_utils_EventTarget.js.html#l32

 

ImageLoader - line 68:  an event dispatch is occurring and the eventArg is being created with two defined properties "type" and "content".. as you can see "content" is being assigned "this".. where this is actually the ImageLoader instance.

Note that the created texture is also being 'cached' or added into PIXI.TextureCache[].. 

 

Link to comment
Share on other sites

  • 2 weeks later...

Is there anyway to load textures in pixi synchronously? Something like:

var texture = PIXI.Texture.fromImage("bunny.png", onComplete);function onComplete() {   var bunny = new PIXI.Sprite(texture);}

Your example is not how synchronous function works, it is asynchronous. http://stackoverflow.com/a/16336405/3552579 explains the difference.

 

// Example Synchronousvar result = database.querySync("SELECT * FROM hugetable");console.log("query finished");console.log("Next line");// Output:// query finished// Next line//Example Asynchronousdatabase.query("SELECT * FROM hugetable", function(rows) {console.log("query finished");});console.log("Next line");// Output// Next line// query finished

Perhaps you can tell your problem and why you need to load textures sync/async, then we can help you.

 

Link to comment
Share on other sites

  • 2 years later...

Bumping this topic because I've come across a reason to load textures synchronously. I need to store the height of the texture immediately after it is loaded. Consider my code here which extends the pixi Sprite object:

 

export abstract class OperationElement extends Sprite {

    private imagePath;

    abstract setPosition(mousePosition?, backgroundHeight?, backgroundWidth?) : void;

    loadTexture(){
        var _texture = PIXI.Texture.fromImage(this.imagePath);
        this.texture = _texture;
        console.log(this.height);
    }

    setImagePath(path : string){
        this.imagePath = path;
    }
}

 

You can see in the loadTexture() function, I'm loading the texture and then assigning it to the texture property. Then, I need to get the height of my object (using console.log as a basic example). Right now, this code will simply log '1' to the console, because everything is running async and the console.log() will fire before the texture is loaded.

I need to wait until the texture is loaded before doing anything else in my program, because everything depends on that height being loaded. How can I make this run synchronously so I can retrieve the height?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...