Create your first 3d scene with Three.js 🪄
Published: 2021-09-18 01:13:40


Hi Everyone, my name is Devang Saklani and Today I'm going to teach you how you can create your first 3d scene with the help of **Threejs**.

## First of all, What is Threejs?
![Threejs logo](https://miro.medium.com/max/1400/1*aDcnXab1QC_5KF8JUxDEYA.png)

**Three. js** is a JavaScript library used to create and run / display animated **3D graphics in a web browser using WebGL**. It also acts as an Api for WebGL.
It uses `<canvas>` element to display the scene.

It has made displaying 3d objects in Web browsers far easy. As compared to writing native WebGL, ThreeJS is super easy as well as performant.

## Setting up the Basic Environment

Our first step would be to setup a basic environment for our website. We will use ThreeJS npm package and Webpack to bundle it, but you can also use the cdn link for the package.

 > I won't tell you how to use Threejs with CDN in this project but you can read [official installation docs](https://threejs.org/docs/#manual/en/introduction/Installation) to use this method

Clone this starter webpack template: [Github link](https://github.com/Devang47/webpack-starter-for-blog-post)
and run
```
npm install
or
yarn
```
The cloned repo folder structure should be like this:
![Folder structure](https://drive.google.com/uc?id=1RZ83rRXLdEPZGF-EsBCNjCF28-GBPmLY)
To start webpack server run ` npm run dev ` or ` yarn dev ` 

## Creating Basic Scene
First let's discuss what are we going to do: 
1. Firstly we will import `three` from the package
2. Then we will initialize a new ThreeJS Scene
3. A new camera (for viewing the scene)
4. Creating a 3d cube (our 3d object)
5. Setting up the renderer and the animate function

It is as easy as it sounds! **Let's start**

- Installation:
```
npm i three
or 
yarn add three
```

Now, in script.js
- Import Threejs:
```js
import  *  as THREE from  "three";
```
- Create a new ThreeJS Scene
```js
const scene =  new THREE.Scene();
``` 
-  Camera for viewing scene
```js
const camera =  new THREE.PerspectiveCamera(
	75, // field of view
	innerWidth / innerHeight, // aspect ratio of the canvas / screen
	0.1, 500  // near and far clipping plane respectively
);
camera.position.set(0, 0, 3); // Changing the default position of the camera
```
To know more about these properties follow the [official docs](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera) 
or read [this guide](https://threejs.org/docs/#manual/en/introduction/Creating-a-scene)
- Setting up our cube object
```js
const geometry =  new THREE.BoxGeometry(); // Creating a new Geometry
const material =  new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // Giving it a material
const cube =  new THREE.Mesh(geometry, material); // Combining both things

scene.add(cube); // adding it to the scene
```
> by this time nothing will appear on the screen because nothing is rendered yet, So let's initiate a renderer
- Creating a renderer
```js
const renderer =  new THREE.WebGL1Renderer();	// Creating renderer
renderer.setSize(innerWidth, innerHeight); // Size of canvas element
renderer.setPixelRatio(devicePixelRatio); // Yes pixel-ratio of the screen
document.body.appendChild(renderer.domElement); // Adding canvas element to the html 
```
- Now comes the final step: **Rendering!!**
```js
function  animate() {
renderer.render(scene, camera); // Rendering single frame
cube.rotation.x +=  0.01;		// Rotating on the x and y axis
cube.rotation.y +=  0.01;		// Adding simple animation to our object
controls.update() // Required for smooth camera movement
requestAnimationFrame(animate); // Calling this function again to repeat the process 
}
animate();
```
What's happening is we are creating a self-calling function that will call itself around 60 times a second (depends on the user's Screen and CPU) and will create and display a frame on each render.
In the third line we will rotate the cube to get some simple animations on the scene.

The  screen should look like this:

![cube](https://drive.google.com/uc?id=1x5HJKRJOSJ5YlCIy3TsT_oPvEbno3Gc_)

-  Wanna add controls to the scene? 
In order to add Mouse Controls to the Scene we will use OrbitControls 
```js
import  { OrbitControls }  from  "three/examples/jsm/controls/OrbitControls";// import at the top

//  ... camera, renderer

const controls =  new  OrbitControls(camera, renderer.domElement); // Creating controls
controls.enableDamping =  true; // Enabling the smooth camera movement effect
```
If any error occurs just leave a comment below I'll surely try to reply ASAP.


That's it, You've finally created your first ThreeJS scene! Congratulations! 🎉
![Congratulations](https://i.giphy.com/media/xT0xezQGU5xCDJuCPe/200w.webp)

Well this was pretty basic, Now lets add something interesting!

Change `MeshBasicMaterial` to `MeshNormalMaterial`. 
The screen should look like this:
![cube with colors](https://drive.google.com/uc?id=1lWGP4PdNqf2R8wdw1LmDeJjjdxqT8zst)
Read more about materials here: [Official docs](https://threejs.org/docs/#api/en/materials/MeshNormalMaterial) or [here](https://threejsfundamentals.org/threejs/lessons/threejs-materials.html)

The final script should look like this:
{% gist https://gist.github.com/Devang47/c8e422c54543b20bc72748f323ef348f.js %}
Check it live here: [click here](https://basic-3d-scene-with-threejs.netlify.app/)

You can add more cubes, spheres, triangles as well as your Custom bleder models! in ThreeJS.

This is the most recent website I build using ThreeJS: [click here](https://threejs-portfolio-website.netlify.app) and TBH it's pretty basic and easy.
![scene](https://drive.google.com/uc?id=1ylKSd1_zmpdMPEiLxRoRxSIp1LpbG62Y)


If you are interested in learning ThreeJS I'd recommend reading the [official docs](https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene) or  going to [Threejs Fundamentals](https://threejsfundamentals.org/) and if you're really interested in WebGL and ThreeJS I'd recommend you to watch [this course](https://threejs-journey.xyz/) by [Bruno Simon](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwiHndLlmobzAhXVH7cAHRJGCs0QFnoECA4QAQ&url=https://threejs-journey.xyz/&usg=AOvVaw3_Q2G5Wfctal9GtickWuz6). He is one of the finest ThreeJS developers.
 
 Thanks for reading this post and if you got any errors, just leave a comment below or [mail me](mailto:devangsaklani@gmail.com).

A post by [Devang Saklani](https://twitter.com/DevangSaklani). Hope my efforts were of any help.😇