Render Targets
A render target is a buffer that can be rendered to.
By default the render target that a renderer uses is the canvas that is passed into its constructor.
const renderer = new WebGLRenderer({ canvas,});
renderer.render(scene, camera); // render to the canvasCreating a Render Target
Section titled “Creating a Render Target”You can create a render target to render the scene, or any other scene for that matter, to something other than the canvas.
const target = new WebGLRenderTarget(width, height);The target’s size can be updated using the setSize method.
declare function getWidth(): number;declare function getHeight(): number;
target.setSize(getWidth(), getHeight());To draw the scene to the target, the renderer’s target needs to be updated.
renderer.setRenderTarget(target);renderer.render(scene, camera); // render to the render targetWhen setRenderTarget is passed null, the target is set to the canvas.
renderer.setRenderTarget(null);Using the Target’s Texture
Section titled “Using the Target’s Texture”The render target’s texture is just like any other texture and can be passed as input into three.js materials.
const material = new MeshBasicMaterial({ map: target.texture,});If a mesh in the scene requires the target’s texture for its material, you’ll get a WebGL warning in the console. To mitigate this, you can temporarily hide the mesh, render the scene, then unhide the mesh and render again.
const render = () => { mesh.visible = false;
const last = renderer.getRenderTarget();
renderer.setRenderTarget(target); renderer.render(scene, camera);
mesh.visible = true;
renderer.setRenderTarget(last); renderer.render(scene, camera);};The texture can also be passed as a uniform into a custom shader. This makes it easy to do simple post-processing. See the post-processing article for more information.
const uSceneTexture = new Uniform(target.texture);
const material = new RawShaderMaterial({ fragmentShader, uniforms: { uSceneTexture, }, vertexShader,});