Setting image from http resource using cc.loader.load

Hi,

Why this is not working? How to I set a spriteFrame from a downloaded image?

Getting this error:
NetworkCtrl.js:53 Uncaught TypeError: Cannot read property ‘spriteFrame’ of undefined
at CCLoader. (NetworkCtrl.js:53)
at CCLoader.js:253
at utils.js:85

This is my code:

cc.Class({
extends: cc.Component,

properties: {
   
    testimg:{
        default: null,
        type: cc.Sprite
    } 
},

LoadImageOnline: function () {
    var newTexture = new cc.Texture2D();
    
    cc.loader.load('http://192.168.1.70:3000/mountains.jpeg', function (err, tex) {
        
             this.testimg.spriteFrame.setTexture(tex);
            });

});

How to make this work?
Updated code but getting this error:
NetworkCtrl.js:61 Uncaught TypeError: st is not a function
at CCLoader. (NetworkCtrl.js:61)
at CCLoader.js:253
at utils.js:85

From the docs: the load method can handle callback function:

Updated the code to include this:

setTex: function (t){
this.testimg.spriteFrame.setTexture(t);
},

loadImageOnline: function (){
    var st = this.setTex;

    cc.loader.load('http://192.168.1.70:3000/mountains.jpeg', function (err, tex, st) {
        cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D));
       cc.log('tex width: ' + tex.width );
       cc.log('tex loaded: ' + tex.loaded );
       st(tex);
        //this.testimg.spriteFrame.setTexture(tex);
       });

},

Have you tried this?

cc.loader.load('http://192.168.1.70:3000/mountains.jpeg', function (err, tex) {
        this.testimg.spriteFrame = new cc.SpriteFrame(tex);
   });

Still getting the same error.

Well, it looks like it’s a problem with your code, since this.testimg is undefined… Have you set the reference to this sprite on the editor?

50%20AM

Checked again, I’m sure its referenced in the editor.

You are using the ‘this’ keyword inside a function scope, it will reference the inner scope, not your class.
Try:

cc.loader.load('http://192.168.1.70:3000/mountains.jpeg',  (err, tex) => {
    this.testimg.spriteFrame = new cc.SpriteFrame(tex);
});

or get a reference for your desired this scope before:

var that = this;
cc.loader.load('http://192.168.1.70:3000/mountains.jpeg',  function (err, tex) {
    that.testimg.spriteFrame = new cc.SpriteFrame(tex);
});
5 Likes

According to the documentation.


proto.load = function(resources, progressCallback, completeCallback) {

I should be able to pass in a callback function ‘completeCallback’. I’m still trying to get this it work.

See my answer above

It works.

Furthermore,

Both of these work:

if you don’t already have a default image in the spriteFrame in editor, you have to use this.
that.testimg.spriteFrame = new cc.SpriteFrame(tex);

otherwise this will be ok.
that.testimg.spriteFrame.setTexture(tex);

You should probably set the post that helped you to “solved”

Yes I should, its set.

1 Like

solved for me. thanks. keep helping.

1 Like