Anyone know how to change the scene ratio using react-babylonjs?

Here is our babylon scene in the right side which is in the landscape ratio. We want it to be in portrait style like the one picture in the left side. @brianzinn

The ratio of the Babylon scene will be the ratio of the canvas so just change the canvas size

2 Likes

Hi @carolhmj

Do you mean I need to change the canvas.style.width .

Below is the code where width and height changed in percent.

  function onSceneMount(e: any) {
    const { canvas, scene } = e;
    scene.clearColor = new Color4(3, 1, 1);

    setScene(scene);
    canvas.style.width = "100%";
    canvas.style.height = "100%";
  }

Thank you @carolhmj

The below code is working fine. But the objects inside are geting thinner or squeezed according to canvas size. The images below with 1000px width and 200px width.

 function onSceneMount(e: any) {
    const { canvas, scene } = e;
    scene.clearColor = new Color4(3, 1, 1);

    setScene(scene);
    canvas.style.width =  200 + "px";
    canvas.style.height =  800 + "px";
  }


You need to add a resize listener in your canvas, see the example Getting Started - Chapter 1 - Setup Your First Web App | Babylon.js Documentation (babylonjs.com)

1 Like

Thank you @carolhmj below code is working for me.

    if (scene) {
      scene.getEngine().runRenderLoop(() => {
        if (scene) {
          scene.render();
          scene.getEngine().resize();
        }
      });
    }
  }, [scene]);```

You don’t need to resize in the render loop. Once after you explicitly set it ought to be enough. I commented out a ResizeObserver on the canvas element for some reason. Would you mind testing @Chaitanya_Yanamala if a new version fixes that?

1 Like

Just a note to say there is a difference between using canvas.style.width and canvas.width

See <canvas>: The Graphics Canvas element - HTML: HyperText Markup Language | MDN

and

Okay sure I will check it out.