Hi!
I’m trying to dynamically modify the size of my canvas and make the BabylonJS engine modify the aspect ratio in the process. In a regular window resize (dragging the sides of the window) the aspect ratio is updated to work fine with the current size of the canvas, but when I trigger a maximize/minimize the resize function does not modify the aspect ratio. My code:
export default ({antialias, engineOptions, adaptToDeviceRatio, sceneOptions, onSceneReady, onRender, ...rest}:BabylonjsProps & React.CanvasHTMLAttributes<HTMLCanvasElement>) => {
const reactCanvas = useRef(null);
const [canvasStyle, setCanvasStyle] = useState({
width: '100%',
height: '100%'
});
// set up basic engine and scene
useEffect(() => {
const { current: canvas } = reactCanvas;
if (!canvas) return;
const engine = new Engine(canvas, antialias, engineOptions, adaptToDeviceRatio);
const scene = new Scene(engine, sceneOptions);
if (scene.isReady()) {
onSceneReady(scene);
} else {
scene.onReadyObservable.addOnce((scene) => onSceneReady(scene));
}
engine.runRenderLoop(() => {
if (typeof onRender === "function") onRender(scene);
scene.render();
});
const resize = () => {
const canvasRect = document.getElementsByTagName('canvas')[0].getBoundingClientRect();
const contentPos = document.getElementById('main-content').getBoundingClientRect();
setCanvasStyle({
width: contentPos.width + 'px',
height: window.innerHeight - canvasRect.y + 'px'
})
scene.getEngine().resize();
};
if (window) {
window.addEventListener("resize", resize);
}
return () => {
scene.getEngine().dispose();
if (window) {
window.removeEventListener("resize", resize);
}
};
}, [antialias, engineOptions, adaptToDeviceRatio, sceneOptions, onRender, onSceneReady]);
return (
<canvas ref={reactCanvas} {...rest} style={canvasStyle} className="p-5" />
)
};
This is tested in Chrome and Edge, but doesn’t work for either browser. Does anyone have experience with this?