Capítulo 843 de 859
Making a three.js app responsive means letting CSS control the canvas's display size while keeping the camera aspect and the renderer's internal resolution (drawing buffer) in sync with that display size — plus deliberate choices around high-DPI displays, where rendering at full device resolution can be far more expensive than it's worth.
width: 100%; height: 100%; display: block (with html/body sized to fill the viewport) lets the canvas resize like any other element — no three.js code changes needed for it to work inside different layouts (sidebars, inline in a document, etc.).canvas.clientWidth/clientHeight each frame and updating camera.aspect (plus updateProjectionMatrix()) prevents the classic "stretched cube" bug.renderer.setSize(width, height, false) sets the internal resolution without letting three.js also override the CSS size (the false argument is important).setSize when the computed size actually differs from the canvas's current internal size, since browsers treat canvas resizing specially and unnecessary resizes aren't free.renderer.setPixelRatio() vs. manual scaling: setPixelRatio is convenient but decouples the size you asked for from the size three.js actually uses internally, which causes confusion anywhere you need the real drawing-buffer size (post-processing, gl_FragCoord-based shaders, screenshots, GPU picking); computing devicePixelRatio-scaled dimensions yourself and passing them directly to setSize keeps "the size I asked for" and "the size in use" identical.function resizeRendererToDisplaySize(renderer, maxPixelCount = 3840 * 2160) {
const canvas = renderer.domElement;
const pixelRatio = window.devicePixelRatio;
let width = Math.floor(canvas.clientWidth * pixelRatio);
let height = Math.floor(canvas.clientHeight * pixelRatio);
const pixelCount = width * height;
const renderScale = pixelCount > maxPixelCount ? Math.sqrt(maxPixelCount / pixelCount) : 1;
width = Math.floor(width * renderScale);
height = Math.floor(height * renderScale);
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) renderer.setSize(width, height, false);
return needResize;
}
setPixelRatio.width/height: 100%, display: block) rather than hardcoding pixel dimensions in JS.camera.aspect to the canvas's CSS size every frame, calling updateProjectionMatrix() after any change.renderer.setSize(width, height, false) — the false prevents three.js from overriding the CSS size you already set.renderer.setPixelRatio(), so the size you requested and the size actually in use never diverge.setSize/setPixelRatio, the core APIs this chapter is built around.