If you are using Three.js (or any canvas) and your game isn’t going to take up the entire browser window, you would most likely want your game canvas and contents to scale uniformly as the browser window changes.
Here’s how you can get started achieving this effect.
1. Define your “native” size
This is the size you want your canvas to be when the browser window is maximized. You would define the size of the scene in your start() or init() method and treat them like constants.
1
2
3
4
5
6
7
8
9
10
11
| function init()
{
//create the scene and set the scene size
scene = new THREE.Scene();
WIDTH = 640;
HEIGHT = 400;
//for fullscreen
/* WIDTH = window.innerWidth;
HEIGHT = window.innerHeight; */
}
|
2. Add an event listener to handle the window being resized
1
| window.addEventListener('resize', function(){ ... });
|
Within the resize method, we need the aspect ratio of our native size as well as the aspect ratio of the browser window. The aspect ratio of the native size can be calculated beforehand (when the native width and height are set), but the aspect ratio of the browser should be updated every time the window changes
1
2
3
4
5
6
7
| window.addEventListener('resize', function()
{
var aspect = WIDTH/HEIGHT; //native aspect ratio;
var browserWidth = window.innerWidth;
var browserHeight = window.innerHeight;
var browserAspect = browserWidth/browserHeight;
});
|
3. Compare aspect ratios to prevent distortion
If the browser ratio is larger than the native aspect ratio, it means that the browser window is too wide. If it is smaller, it means that the browser is elongated.
Assign the recalculated values to new variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| window.addEventListener('resize', function()
{
// ...previous code goes here
if(browserAspect > aspect)
{
browserWidth = browserHeight * aspect;
}
else if(browserAspect < aspect)
{
browserHheight = browserWidth / aspect;
}
resizedWidth = browserWidth;
resizedHeight = browserHeight;
});
|
4. Check that the new resized values are not larger than the native sizes.
1
2
3
4
5
6
7
8
9
10
| window.addEventListener('resize', function()
{
// ...previous code goes here
if(resizedWidth > WIDTH)
resizedWidth = WIDTH;
if(resizedHeight > HEIGHT)
resizedHeight = HEIGHT;
});
|
5. Assign the new width and height to the renderer and update the camera aspect and projection.
1
2
3
4
5
6
7
8
| window.addEventListener('resize', function()
{
// ...previous code goes here
renderer.setSize(resizedWidth, resizedHeight);
camera.aspect = resizedWidth / resizedHeight;
camera.updateProjectionMatrix();
});
|
6. TA-DA!
Now you should have a canvas that resizes uniformly when the browser window changes.
I hope this was helpful!