New size of Canvas after resize

Hi, it’s more a question about JS and browsers, but maybe someone can help me.
I want to scale the text inside a UI panel based on the size of the canvas (which is tied to the window size).
Using the following function, which is tied to the resize event of the window, will resize the text correctly. This works fine as long as the window is resized by dragging the corners of the browser. But clicking the maximize or normalize buttons in the program bar, or tiling the window with super-key+arrow, will not update the canvas width parameter . The console.log() outputs the last width of from before the resize not the one after the resize of the window.

The (not so) funny thing is, when I output the html element (this.context.renderer.domElement), it has the correct new size, but when I access its parameters (newWidth ) it gives the outdated one.

import { Behaviour, GameObject, NeedleEngine, RectTransform, serializable, Text, ViewDevice } from "@needle-tools/engine";

export class NeedleTextSizeFromSceenSize extends Behaviour {

    @serializable(Text)
    public textfield: Text | null = null;
    public fontBaseScreenSize: number = 1920;
    private fontSizeDefault: number = 0;

    awake(): void {
        this.fontSizeDefault = this.textfield?.fontSize ? this.textfield.fontSize : 14;
        this.changeFontSize();
        window.addEventListener('resize', (event) => {
            this.changeFontSize();
        });
    }

    changeFontSize(): void {
        let newWidth = this.context.renderer.domElement.width;
        console.log("changeFontSize", newWidth, this.fontBaseScreenSize, this.fontSizeDefault);
        if (!this.textfield)
            return;
        let canvasToBaseRatio : number = newWidth / this.fontBaseScreenSize;
        if (this.textfield)
            this.textfield.fontSize = this.fontSizeDefault * canvasToBaseRatio;
    }
}

Thankful for any help
Rob

Original Post on Discord

by user 689743366355025931

Does it work work with this.context.domElement.width instead? Might be a case where the canvas (which is controlled in a similar way by us) isn’t rescaled yet but gets scaled later in the frame. The needle-engine element itself should already have the right size though.

it seems to be the case with clientWidth :smile:
It makes no difference between:
this.context.renderer.domElement.clientWidth
or
this.context.domElement.clientWidth
both are updated on every resize.
The problem seems to be this.context.renderer.domElement.width thats not always get updated.

My final function that worked:

    changeFontSize(): void {
        if (!this.textfield)
            return;
        let newWidth = this.context.domElement.clientWidth;
        let canvasToBaseRatio : number = newWidth / this.fontBaseScreenSize;
        this.textfield.fontSize = this.fontSizeDefault * canvasToBaseRatio;
    }

Thank you!

by user 689743366355025931

Glad you figured it out!