Reference HTML element that defines available space for the canvas
Three.js canvas element to fit within the container
Original canvas width for aspect ratio calculation
Original canvas height for aspect ratio calculation
Automatically adjusts canvas CSS styling to fit within the specified container while maintaining original aspect ratio through letterboxing or pillarboxing. Canvas pixel dimensions and rendering performance remain unchanged.
const container = document.getElementById('canvas-container') as HTMLElement;
const canvas = document.getElementById('webgl-canvas') as HTMLCanvasElement;
// Fit canvas within container maintaining 16:9 aspect ratio
resizeCanvasStyle(container, canvas, 1920, 1080);
// Handle window resize events
window.addEventListener('resize', () => {
resizeCanvasStyle(container, canvas, 1920, 1080);
});
// Use different containers for different layouts
const sidebar = document.querySelector('.sidebar') as HTMLElement;
resizeCanvasStyle(sidebar, canvas, 800, 600);
Performance Considerations:
Layout Behavior:
clientWidth
and clientHeight
width
and height
properties for styling
Fits a canvas element within its parent container while preserving aspect ratio.