How to Render Three.js with a Transparent Background
Rendering a Three.js scene with a transparent background allows you
to overlay 3D graphics seamlessly on top of standard HTML elements, such
as text, images, or CSS gradients. This guide provides a
straightforward, step-by-step walkthrough on how to configure the
Three.js WebGLRenderer and adjust CSS properties to achieve
a fully transparent canvas, enabling seamless integration between 3D
elements and web design.
To render a transparent Three.js scene over HTML elements, you must configure the renderer, ensure the scene background is empty, and position your canvas using CSS.
Step 1: Enable Alpha in the WebGLRenderer
When initializing the WebGLRenderer, you must explicitly
pass an options object with the alpha property set to
true. By default, this value is false, which
renders a solid black background.
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);Step 2: Configure the Clear Alpha (Optional)
Once alpha: true is set, the renderer default background
opacity is set to 0 (fully transparent). If you want to
define a custom background color with partial transparency, you can use
the setClearColor method:
// Sets the background to black with 0% opacity (fully transparent)
renderer.setClearColor(0x000000, 0);
// Example: Sets the background to red with 50% opacity
// renderer.setClearColor(0xff0000, 0.5);Step 3: Ensure the Scene Background is Null
Do not assign a color or texture to the scene’s background property, as this will override the renderer’s transparency settings. Ensure your scene setup does not contain the following line:
// Do NOT do this if you want transparency:
// scene.background = new THREE.Color(0xffffff);If you must clear a previously set background, set it back to
null:
scene.background = null;Step 4: Position the Canvas with CSS
To see your HTML elements behind the Three.js canvas, use CSS to
position the canvas element absolutely or fixedly, and place it behind
or in front of your content using z-index.
Here is an example setup:
<!-- Underlying HTML Content -->
<div class="content">
<h1>This is HTML Content</h1>
<p>The 3D scene is rendering on top of this text.</p>
</div>
<!-- Three.js Canvas Element container (if generated by JS) -->
<style>
body {
margin: 0;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
overflow: hidden;
}
/* Style the HTML content */
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-family: sans-serif;
color: #333;
text-align: center;
pointer-events: none; /* Allows mouse interactions to pass through to the 3D scene */
z-index: 1;
}
/* Position the WebGL Canvas */
canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2; /* Renders 3D objects on top of the text */
pointer-events: auto;
}
</style>