It's quite disheartening to see the other solutions, as they seem to be in constant conflict with the browser instead of working alongside it.
The most effective approach for resizing three.js is to code it in a way that simply adapts to the size set by CSS on the canvas element. This ensures that your code remains functional regardless of how you use the canvas, eliminating the need for adjustments in different scenarios.
Initially setting the aspect ratio serves no purpose since we will be updating it based on the canvas size changes, making it redundant to set it multiple times in the code:
// There's no reason to set the aspect here because we're going
// to set on resize anyway
const camera = new THREE.PerspectiveCamera(70, 1, 1, 1000);
We then incorporate code that resizes the canvas to match its display dimensions:
function resizeCanvasToDisplaySize(force) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (force || canvas.width !== width || canvas.height !== height) {
// Ensure smooth coordination with the browser by passing false
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
// Update any render target sizes here
}
}
Include this function in your rendering loop and call it once during initialization:
function animate(time) {
time *= 0.001;
resizeCanvasToDisplaySize();
mesh.rotation.x = time * 0.5;
mesh.rotation.y = time * 1;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resizeCanvasToDisplaySize(true);
requestAnimationFrame(animate);
For achieving fullscreen display, the following CSS rules are all that's required:
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
Four examples showcasing different scenarios are provided below. The only varying factor among them is the CSS styling and the method of creating the canvas, while keeping the code unchanged:
Example 1: Fullscreen display where we create the canvas
[Code snippet for Example 1]
Example 2: Fullscreen canvas created by three.js
[Code snippet for Example 2]
Example 3: Inline canvas
[Code snippet for Example 3]
Example 4: Canvas at 50% width (like a live editor)
[Code snippet for Example 4]
The implementation above functions seamlessly without referencing window.innerWidth
or window.innerHeight
, demonstrating its versatility across various scenarios.
Why avoid using the resize
event? There are instances where no resize event is triggered even though the canvas size changes, such as when implementing a 2-column editor with a movable divider between columns or scaling the canvas based on nearby content. In such cases, relying solely on the resize
event may not suffice.