Skip to main content

Adding the renderer

The renderer is what translates your 3D scene into pixels on your display. It is the bridge between the mathematical models of the objects in your scene and the hardware that generates images on your display.

You'll use a WebGLRenderer for this project. WebGL is a low-level programming interface supported by modern browsers. There are other types of renderers in three.js, but they are for specific, advanced use cases that aren't covered in this tutorial.

The function below accepts the ID of an HTML <canvas> element as its only parameter. It then queries the HTML for that element and passes it to the renderer when you create it on the next line.

Note that one of the options passed to the WebGLRenderer is alpha: true. This option tells the renderer to use a transparent background and allow the background color you specified in your CSS to show through. If you don't set this option, the background of the scene will be black.

The function then sets its size to fill the entire browser window. Setting the pixel ratio ensures that the image isn't blurry if you're using a high resolution display (HiDPI or "Retina" displays).

Finally, the function returns the renderer object it created.

function setUpRenderer(elementId) {
const canvas = document.querySelector(elementId);
const renderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true });

renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);

return renderer;
}