Three.js is a super cool library that lets us create 3D objects and scenes in the browser. I’ve been really excited about using it since I started working in web development. My goal here is to go over the basics, so that you can get started with three.js today (And build more cool stuff in the future!).
WHAT WE’LL BE BUILDING:
We’re going to start out with three.js by building a simple scene. In this scene is going to be a wireframe sphere that spins:
I’ve split up this tutorial to make it a bit easier to follow:
- Part 1 will be about creating a scene and placing the object in the scene
- Part 2 will be about styling and animating the scene
LETS GET STARTED
To create this scene there are only 4 things we need:
- A Renderer (Canvas element)
- A Scene
- A Camera
- A mesh (Object to view)
I like to think of working in three.js as creating a movie. We need our actors (mesh objects), a camera to film with, and a scene where the action takes place. And then for a viewer to see what we’ve created, they need something to view it with. In real life this could be a television, theatre, or computer, but here we’re going to use an HTML
As of writing this, three.js is in version 76, you can grab the most up to date version here.
In order to initialize our scene, we must first create the things we need, we’ll do this by creating our renderer, camera, scene, and mesh inside of an init() function:
Once our renderer is in place, we can create our scene and camera. The camera accepts 4 arguments:
- The Field of view
- The aspect ratio Determines how our camera will play on our renderer. Usually this will be the width/height so the image is not squished.
- Near clipping plane How far away will we start viewing the scene.
- Far clipping place How far away will we stop viewing the scene.
Unless we specify it, the postition of our objects will be placed at (0,0,0) - That’s (x,y,z). Let’s position our camera to ensure it’s outside of our object (Very difficult to view our object when our camera is inside!):
Now that our camera is set up, lets add our object. An object needs the following:
- Geometry - This tells our object what shape it should take.
- Material - What our shape should look like.
- Mesh - This combines our geometry and material so we can add it to the scene.
Finally, we need to render the scene:
Now that we have our functions in place, we just need to call them.
You should see something very similar to what is displayed below:
If you don’t see a white sphere on a black background, feel free to download the finished file and compare code.
This might not look like much, but it’s a great start to putting together the pieces of three.js. In the next part, I’ll show you how to style the sphere, and how to make it spin!