ThreeJS Setting the Right Aspect Ratio for the Camera

One quick note for myself and anyone who will ever use this…

If you are working with an abnormal size canvas, you need to do some math to set the size of the renderer to be correct with the aspect ratio:

[pastacode lang=”javascript” manual=”let%20rect%20%3D%20this.renderer.domElement.getBoundingClientRect()%3B%0A%09%09camera.aspect%20%3D%20rect.width%20%2F%20rect.height%3B%0A%09%09camera.updateProjectionMatrix()%3B%0A%09%09renderer.setSize(%20rect.width%2C%20rect.height%20)%3B” message=”” highlight=”” provider=”manual”/]

Basically, you are working out the bounding box in which the scene will exist. To do that, we need to give the camera an aspect ratio and a size for the renderer. Setting the size on the renderer is easy; just send the width and height. The aspect ratio is also pretty easy; just divide the width by the height and you are good to go.

Both the width and height can be found by using “getBoundingClientRect()”.

NOTE: This site is all about helpful hints tricks and tips. The posts lately have been short on purpose. For one, I’m busy AF and don’t have the time to post anything of great detail. Additionally, I believe in simplicity. You can visit, find something helpful and move on with your life.

As always I appreciate your feedback, please leave a comment if you feel I’m leading people down a less than idea path or just comment because you like talking IDC.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.