Matthew Lundstrom
Matthew Lundstrom

Reputation: 117

Adjust Three.js camera FOV based on width

The below standard Three.js resize code scales the scene in relationship to the DOM element's height. If the element height decreases then the scene scales proportionally to keep the model in view. However, when the element's width decreases the scene does not scale and the model gets cropped by the element. How can I have the scene scale with the element's width as it does with height?

window.onresize = function(event) {
    camera.aspect = $(threeContainer).width() / $(threeContainer).height();
    camera.updateProjectionMatrix();
    renderer.setSize($(threeContainer).width(), $(threeContainer).height());
};

Upvotes: 0

Views: 1099

Answers (1)

TheJim01
TheJim01

Reputation: 8866

The easiest way is to fake it.

You'll want to set your canvas size based on the aspect ratio of your container. Consider these aspect ratios:

  • W = 800, H = 600, AR = 4/3 = 1.333
  • W = 500, H = 500, AR = 1
  • W = 600, H = 800, AR = 3/4 = 0.75

So if your aspect ratio is less than 1, you need to adjust the height of the canvas to compensate for the fact that it's a vertical FOV.

if(w/h < 1){
    renderer.setSize($(threeContainer).width(), $(threeContainer).height() * (w/h));
}

You'll also need to apply styling to renderer.domElement to center it vertically in threeContainer. This centering won't be noticeable when the container is wider, but will give it the appearance of scaling correctly when the container is taller.

Upvotes: 1

Related Questions