Where to begin with ThreeJs?

Hasini Senanayaka
3 min readJan 16, 2021

Let’s start learning ThreeJs. You do not need to be an expert in 3D graphic design. Your first program is just few minutes away…

First let’s begin with Hello Cube app. There you need two files. Index.html file and three.js library.Create separate folder called js/ and put three.js file in it. Folder structure should be like below. There I have three.min.js file which can be used in low performance PCs. As threejs is JavaScript library I use VS code as my IDE.

File structure

So Let’s start coding in index.html.

<!DOCTYPE> 
<html>
<head>
<meta charset="utf-8">
<title> Hello Cube </title>
<style> body { margin: 0; } </style>
</head>
<body>
<script src="js/three.js"></script>
<script>
// This area is used to add threejs controls.
</script>
</body>
</html>

Then we have to embed three things: scene, camera and renderer. To actually be able to display anything with three.js these 3 are must. So let’s add them. Keep in mind following code segments should go between <script> tags which has been already allocated for threejs controls.

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 );

As last part we have to add renderer element to our HTML document. This will create <canvas> element and it is used to display the scene to user.

Next part is adding 3D elements. Let’s how to carry out this.

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 = 10;

Here this creates Box and adds green color to it’s surface. To view our box we move camera towards us little bit.

Finally we have to render our scene. To be more realistic I will add animation to cube.

function animate() {  
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();

Tada!!! your application is ready… Now let’s run our application. Here I use live server. Go to extensions and from there you can install live server.

live server extension

Then go to index.html and right click on open with live server.

How to start live server

Congratulations!! Here is your app running in browser…

This is end simple threejs tutorial. Hope you grab something :) .

--

--