Is There a Way to Update the Aspect Ratio in the Animation Loop?

Hello, thanks for taking the time to read this post. I was wondering, is there a way to update the aspect ratio in the main animation loop, since if a user were to resize their window, it would squish or stretch the shape. Here’s my CodePen, since I don’t feel it would be appropriate to post the raw code for it on here. https://codepen.io/Logan-Paxton/pen/jENKoOR

Yes. You just need to update the camera’s aspect and call camera.updateProjectionMatrix() whenever the window size changes. You can do that inside your render/animation loop or, more commonly, in a window.onresize event listener. For example:

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

// If you want to do it each frame, just do:
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);

But repeatedly doing it in each frame can be expensive, so a resize event handler is typical. For instance:

window.addEventListener('resize', onWindowResize);
5 Likes

Ah, thanks it worked!