Three.js Basics

Welcome to the Three.js Fundamentals basics. Now that we understand the basics of 3D grpahics, let's move onto Three.js.

Example Scene

Let's take a look at the example scene.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>My first three.js app</title>
		<style>
			body { margin: 0; }
		</style>
	</head>
	<body>
		<script src="js/three.js"></script>
		<script>
			const scene = new THREE.Scene();
			const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

			const renderer = new THREE.WebGLRenderer();
			renderer.setSize( window.innerWidth, window.innerHeight );
			document.body.appendChild( renderer.domElement );

			const geometry = new THREE.BoxGeometry();
			const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
			const cube = new THREE.Mesh( geometry, material );
			scene.add( cube );

			camera.position.z = 5;

			const animate = function () {
				requestAnimationFrame( animate );

				cube.rotation.x += 0.01;
				cube.rotation.y += 0.01;

				renderer.render( scene, camera );
			};

			animate();
		</script>
	</body>
</html>

Let's remove the HTML and just focus on the JavaScript.

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );

There are some concpets that might be new.

THREE.Scene()

Where you place objects, lights, cameras, etc.

THREE.PerspectiveCamera()

A type of camera

THREE.WebGLRenderer()

The renderer that makes it possible to render 3D in the browser

THREE.BoxGeometry()

A type of geometry (a box)

THREE.MeshBasicMaterial()

A type of material (not texture)

THREE.Mesh()

The mesh consists of a geometry and material

In the snippet above, we have created a green cube.

Important Concepts

BufferGeometry

In short, BufferGeometry is a "faster" way to represent geomtry. It uses math and magic to represent the 3D geometry. Take a look at the docs or Three.js Fundamentals for a deep dive into this topic.

BufferGeometryUtils

Take a look at the docs for more information.

Materials

Three offers many types of materials, see the docs for more info.

Notice that some meterials are linked to a type of 3D object. For example, LineBasicMaterial and LineDashedMaterial belogns to a line.

Recall the chapter about 3D Basics. We are intrested in edges and meshes. You can find more information over at the Three.js Fundamentals.

Stuff to Consider

Last updated