How to get pixel width for 100% width element

Hello again :slight_smile:

I have a rectangle in my GUI that has its with set to 100%. I want to arrange the controls inside this rectangle based on its pixel width, but the pixelWidth property is 0 on the first render.

I added this code:

engine.onResizeObservable.add(function () { redoLayout(); });

Which does redo the layout when I resize my window, but the initial layout is wrong because the rectangle’s pixelWidth is 0 to begin with.

Is there an engine observable that I can hook into that will fire after the pixelWidth has been calculated from the 100% width setting?

I think it’s 0 before the first render?

You can try a setTimeout(redoLayout, 0) or BABYLON.Tools.SetImmediate(redoLayout).

Yes, you are right, it it 0 before the first render.

The setTimeout(redoLayout, 0) method works on my computer. Is this guaranteed to work in all situations? It seems a bit weak to me to rely on a time delay. Different devices, different browsers, future versions of browsers etc…

I was hoping that the Babylon engine might have an observable for post render that would be more reliable.

Yes it is. In fact it is not a timer, the 0 value means to execute the code at the next micro javascript task. That means the current thread of execution is finished first, then the code of the setTimeout(..., 0) will be executed. As the current thread of execution is the Babylonjs rendering, you are sure you will have had a frame rendered (and so the pixelWidth value updated) when your timeout code is executed.

You can use scene.onAfterRenderObservable. You also have engine.onEndFrameObservable.