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);
});
},
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);
});
…
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.