Loading Image from URL

How do you load an external image as a sprite frame of a prefab?

var tex = cc.TextureCache.getInstance().addImage(“http://www.abc.com/t1.png”);
icon.sprite.setTexture(tex);

Pops an error “Cannot read property ‘getInstance’ of undefined.”

Hi @adikhel. You need to use cc.loader.load().
You can read about it here: https://docs.cocos2d-x.org/creator/manual/en/scripting/load-assets.html
(find section How to load remote assets or files in device)

Followed the instructions in the link.

Defining the type as ‘Texture2D’ gives me ‘Type Error’ in the editor.

Can not indicate the ‘type’ attribute for “loadImageIcons.texture”, which its default value is type of string.

scrn1

This is what I am doing. Am I missing something?

spriteFrame.setTexture(texture) gives me this error:

Uncaught DOMException: Failed to execute ‘open’ on ‘XMLHttpRequest’: Invalid URL

cc.loader.load(iconUrl, function (err, texture) {
            var icon = cc.instantiate(self.gameIconPrefab);
            icon.getComponent(cc.Sprite).spriteFrame.setTexture(texture);
            self.webViewContent.addChild(icon);
        });
  1. If you are trying to load texture from URL you don’t need texture property of component.
  2. Type error is because default value of texture property should be null not empty string ("").
  3. As I can understand from your error log: image URL is invalid :). Try to open this url in browser first.
  4. cc.loader.load() code looks ok.

The image url works on the browser. If I comment out the line ‘setTexture’, I am able to console.log the encoded string texture data. So there does not seem to be a problem with the url.

I tried to set the default value of texture to null, but that did not work. I believe the default data type will be string, since the encoded texture data is received in string format. Also, the official documentation that you referred to (https://docs.cocos2d-x.org/creator/manual/en/scripting/load-assets.html) defines that datatype to be string.

Still stuck on how to set the texture data to a sprite frame.

cc.loader.load(iconUrl, function (err, texture) {
           var newSpriteFrame = new cc.SpriteFrame(tex);
});

I can’t seem to do this, since spriteFrame takes a resource url and not the texture data directly. Can someone help?

This code works. Thanks for the help @Postelzhuk.

cc.loader.load({id: iconUrl, type: 'png'}, function (err, tex) {
            var icon = cc.instantiate(self.gameIconPrefab);
            icon.getComponent(cc.Sprite).spriteFrame= new cc.SpriteFrame(tex);
            self.webViewContent.addChild(icon);
});