I know how to find Node width but it’s not working properly.
When I add cc.Label component in a Node and try to update ‘String’ value then Node’s width auto changes based on string width but Node width only changes on 2nd update…
How to get Node width immediately after adding cc.Label
var n = new cc.Node();
n.addComponent(cc.Label);
n.getComponent(cc.Label).string = "OK";
otherNodeInScene.addChild(n);
console.log(n.width); //will be 0;
//on 2nd update of otherNodeInScene n node will have updated width equal to content width of string
how I can access immediately the value of width correctly?
how Node adapts it’s width according to cc.Label component string value?
When you create a new node, you instanciate it with default values. In your case there are no width / height yet. New components does not affect the size of a node. Creating new childs to a node wwill not affect the size.
Because a label is a component, It does not have a size property or some sort. You will need to calculate the string size on your own. and than apply it to the parent node.
You may want to use the following method to calculate text size:
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.font = “30px Arial”;
var txt = “Hello World”
ctx.fillText(“width:” + ctx.measureText(txt).width, 10, 50)
ctx.fillText(txt, 10, 100);
LabelWidthIssue.zip (898.2 KB)
Hi,
here is a small test project, where the width of my labels is still 0 after calling the _updateRenderData function. Sorry for late reply.
@Khachatur, try giving at least one frame to the engine’s game loop do its internal stuff. I suggested the following in another similar topic:
const node = cc.find("/Canvas/New Node");
cc.log(node.width); // 100 units (the initial size that I defined in design time).
const label = node.addComponent(cc.Label);
label.string = "TestString";
this.scheduleOnce(() => {
cc.log(node.width); // Here it has been updated to 177.85 units.
});