Creating dynamic text

Hi!

I’m trying a create dynamic text in my app, but the text don’t appears in the screen, in the console logs the text is created i don’t know what to do.

this.screenUI = this.app.root.findByName(‘Icons_Canvas’);

var textMeasure = new pc.Entity();
textMeasure.name = "text";  
    

//button. = new Selector(button, selectionManager);
textMeasure.addComponent('element', {
    type: "text" ,
    anchor: new pc.Vec4(0.5,1,0.5,1),
    pivot: new pc.Vec2(0.5,1),
    preset: "Center",
    width: 256 ,
    height: 256,
    rect: [0,0,1,0.25],
});
textMeasure.element.text = "Hello World";
this.screenUI.addChild(textMeasure);

Thanks!

1 Like

Link to project please?

Edit: Actually, my guess is that you haven’t assigned a font asset to the text element.

1 Like

how I can assign fontasset?

var font = new pc.Asset(‘A Sensible Armadillo.ttf’, “font”, {url: “/Fonts/A Sensible Armadillo.ttf”});
textMeasure.addComponent(‘element’, {
type: “text” ,
anchor: new pc.Vec4(0.5,1,0.5,1),
pivot: new pc.Vec2(0.5,1),
preset: “Center”,
width: 256 ,
height: 256,
fontasset: font,
fontSize: 24,
rect: [0,0,1,0.25],
//textureAsset: buttonAsset
});
console.log(textMeasure.fontasset);

but the log says “undefined”

Are you using the editor or the raw engine?

I’m using the Editor

Upload a font to the editor. The editor will then convert that to a bitmap font asset.

You can then use that bitmap font asset for your text elements.

hmm can you check the project? i can’t see the text https://playcanvas.com/editor/scene/606510

Thanks!

Made some fixes. Please see here: https://playcanvas.com/project/554110/overview/proves-from-forums

var Measures = pc.createScript('measures');


Measures.attributes.add("font", {type: "asset", assetType: "font"});
Measures.attributes.add("text", {type: "string"});


// initialize code called once per entity
Measures.prototype.initialize = function() {
    
    this.screenUI = this.app.root.findByName('Canvas');
    
    console.log(this.screenUI);
 

    var textMeasure = new pc.Entity();
    textMeasure.name = "textMeasure";
    
    textMeasure.addComponent('element', {
        type: pc.ELEMENTTYPE_TEXT ,
        anchor: new pc.Vec4(0.5,1,0.5,1),
        pivot: new pc.Vec2(0.5,1),
        preset: "Center",
        width: 256 ,
        height: 256,
        fontAsset: this.font,
        fontSize: 24, 
        rect: [0,0,1,0.25],
    });
    
    textMeasure.element.text = this.text;
  

    this.screenUI.addChild(textMeasure);
};

Solved! I create a attribute for assign the font in the editor!

Thanks for your reply!!