How to add a background image in Three.js

There are many cases where you may want to use a three.js background image for one of your scenes. In this tutorial, I’m going cover how to add a one using a 2D image. The goal here is to have a static background to a regular 3D scene in three.js. The effect of using a static background can be quite effective in some cases, and I think it works well in the example below.

To get started, I highly recommend following along by checking out the repository below and using the starter branch. I like to add some boilerplate code and assets to each example to speed up the learning process.

Then checkout the starter branch

Lastly, install dependencies and run the server!

Assuming everything went well, you can access your example at the URL below.


Let’s get started!

2D Background Image

In this example we’ll use a standard 640×360 JPEG image as our background image.

Let’s add some global variables at the top of our scripts.js file to make accessing things easy. While I recommend not doing this in a production application… this is not a production application ;). These will cover the material for our background, the additional background scene, and additional background camera.

If you recall from that tutorial, in order for multiple renderers to work accordingly, we need to set autoClear to false.

Since we’ve already defined a TextureLoader with a LoadingManager object, we can call the load method again without needing to instantiate a new object.

What we’re doing here is loading a texture, creating the mesh required for the background image and creating the mesh. Since this is 2D, we can set depthTest and depthWrite to false. Lastly, we are creating the scene and camera for our background image.

the last step for this variation is to go to the animate function and locate the following line:

We need to add to this so it looks like below:

Simply put we are clearing the renderer on each frame (animation loop) and rendering our background first, then our scene on top of it.

Now don’t get confused here – we don’t require multiple renderers. We only need to call the render function twice from that same renderer object.

Once you reach here you have completed the 2d background example, pretty simple right?


Leave a Reply