BabylonJs React 项目 - 调整窗口大小



使用 Hooks(功能组件(而不是类在 React 中执行 BabylonJs Reactjs 教程,我在调整窗口大小时遇到了问题。

// This code block cannot be added in a component...
onResizeWindow = () => {
if (this.engine) {
this.engine.resize();
}
};
... so I rewrote it to 
const onResizeWindow = props => {
if (props.engine) {
props.engine.resize();
}
};
... Then added the listener to the engine hook like below
useEffect(() => {
let engine = new BABYLON.Engine(
canvas,
true,
props.engineOptions,
props.adaptToDeviceRatio
);
let scene = new BABYLON.Scene(engine);
if (typeof props.onSceneMount === "function") {
props.onSceneMount({
scene,
engine,
canvas
});
} else {
console.error("onSceneMount function not available");
}
window.addEventListener("resize", onResizeWindow(props));
});

这是行不通的。我已经尝试了上述代码的一些变体,但它没有适当地调整屏幕大小。还有其他人遇到过这个问题吗?我四处寻找其他问过这个问题但找不到的人。

我希望现在回答这个问题还为时不晚。但我确实遇到了几次同样的问题。这是我的解决方案。

我们需要两部分。

首先,在功能组件上。

<div id="canvasWrapper">
<SceneComponent antialias onSceneReady={onSceneReady} observeCanvasResize adaptToDeviceRatio onRender={onRender} id="my-canvas" />
</div>

我们需要adaptToDeviceRatioobserveCanvasResizeattrribute。

第二

对于CSS。 我们还需要添加这些以确保它填满整个窗口。

html, body {
width: 100%;
height:100%;
margin: 0px;
padding: 0px;
}
#canvasWrapper {
width: 100vw;
height:100vh;
}
canvas{
width: 100%;
height:100%;
margin: 0px;
padding: 0px;
background-color: #000000;
display: block;
}

通过应用这些。您应该能够按预期具有正确的调整大小行为。

最新更新