Apply 3d content on a webpage using three.js library

Apply 3d content on a webpage using three.js library

Duy Le

Apply 3d content on a webpage using three.js library

Many individuals wish to build their own 3D website but may feel unsure of where to begin and have the confidence it would run smoothly. If you’re searching for a way to build 3d websites as a developer then this article will 100% help you.

Apply 3d content on a webpage using three.js library

1) An introduction to Three.js

Three.js is a Javascript library created by Ricardo Cabello. It allows us to deal with 3D visuals in the browser using WebGL in a very basic and natural manner.

2) Fundamentals

Let’s understand the structure of a three.js app.

 

Things to notice about the diagram above.

  • The Renderer is the place where we are going to put the result of our scene. In Three.js we can have multiple scenes and each one can have different objects.
  • The Mesh is made up of a Geometry and a Material.
  • The Geometry — which defines its shape.
  • The Material — which defines its appearance.
// We define a box geometry with width = 1, height = 1, depth = 1
const geometry = new THREE.BoxGeometry( 1, 1, 1);

// We pass the color to the material
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

// Create a mesh
const box = new THREE.Mesh( geometry, material );

// Add a mesh to a scene
scene.add( box );

 

Camera: There are two types. 

  • The first type is referred to as the perspective camera. It is basically the same as real-life cameras. We need four values to make a perspective camera. The first is a vertical field of view (fov). It is the maximum angle of what can be seen through the lens of the camera. The second is the aspect ratio. It represents the proportion of the width and height. The last things are the near and far. It represents the position near or far from the camera.
  • The second type is the orthographic camera. It can be useful for rendering 2D scenes and UI elements.

Light: In this tutorial we will discover two types of light.

  • Let’s start with the most fundamental type of light - Ambient Light
const ambientLight = new THREE.AmbientLight(0x333333, 1);
scene.add(ambientLight);

 

Create a light source, tell it what color it should be (grey in our example), and how intense it should be. This light cannot be used to cast shadows because it has no direction.

 

The last one I would like to mention is SpotLight. This light emits light in the form of a cone. The farther the light source is from the receiving surface, the brighter the light. This light can cast shadows 

const spotLight = new THREE.SpotLight(0xFFFFFF, 1);
scene.add(spotLight);
spotLight.position.set(-100, 100, 0);
spotLight.castShadow = true;
spotLight.angle = 0.2;

 

It has the same constructor as AmbientLight except for a few more attributes castShadow and angle (in the example above I just want to mention 2 attributes). 

Surely you will easily imagine the meaning of these two attributes based on its name. Angle is the maximum extent of the spotlight, in radians, from its direction.

CastShadow if it is set to true light will cast dynamic shadows.

3) Loading 3d models

There are numerous file formats for 3D models, including OBJ, glTF (Graphics Language Transmission Format), and FBX (FilmBoX) (or .OBJ). glTF is the most well-known of them all. 

glTF has two file extensions: .gltf (JSON/ASCII file format) and .glb (binary file format).

 

Now let’s start a new example. You can use gltf sample models with this link
 

import {GLTFLoader} from 
'three/examples/jsm/loaders/GLTFLoader.js';

// resource URL
const imgUrl = new URL('./assets/photo.glb', import.meta.url);

// Instantiate a loader
const assetLoader = new GLTFLoader();

// Load a glTF resource
assetLoader.load(imgUrl.href, 
// Called when the resource is loaded
function ( gltf ) {
  const model = gltf.scene;
  scene.add(model);
  model.position.set(-12, 4, 10);
}, 
// Called while loading is progressing
function ( xhr ) {
  console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// Called when loading has errors
function ( error ) {
  console.log( 'An error happened' );
})

 

glTF is formatted as JSON file. The entirety of the 3D scene is described in this file. You can see it in the image below

 

  • The node is one node in the scene graph hierarchy. It can contain a transformation (e.g., rotation or translation)
  • The mesh describes a geometric object that appears in the scene
  • The material contains the parameters that define the appearance of an object. It usually refers to texture objects that will be applied to the rendered geometry.
  • The texture is defined by a sampler and an image. The sampler defines how the texture image should be placed on the object.
  • The accessor is used as an abstract source of arbitrary data. It is used by the mesh, skin, and animation, and provides the geometry data, the skinning parameters and the time-dependent animation values. It refers to a bufferView, which is a part of a buffer that contains the actual raw binary data.

 

4) Example

I will create a new project so that you can apply it to real life. This project aims to choose products with your favorite color.

 

As I’m a React developer, so I will install these packages to make it easily by using the syntax

 

yarn add three @react-three/fiber @react-three/drei

 

Here is src/App.js:

import {Suspense, useState} from 'react';
import {Canvas} from '@react-three/fiber';

import {OrbitControls, useGLTF} from '@react-three/drei';
 

import './index.css';


export function Model({ ...props }) {
  const { nodes, materials } = useGLTF('/Lamp.gltf')
  return (
   
     
       
     
     
       
     
     
       
     
   
  )
}

function App() {
  const [fabric, setFabric] = useState("#000000")
  const [wood, setWood] = useState("#ffffff")
  const [metal, setMetal] = useState("#e5dcdc")

  return (
   
     


       

Three.js Demo


       

           

               

                 
                   
                   
                   
                 
               

               

                   

                       
                              value={fabric} 
                              onChange={(e) => setFabric(e.target.value)}/>
                       
                     


                   

                       
                                value= {metal}
                                onChange={(e) => setMetal(e.target.value)}/>
                       
                   

                   

                       
                                value={wood} 
                                onChange={(e) => setWood(e.target.value)}/>
                       
                   

                 

           

       

     

   
  );
}

export default App;

 

You can download the sample model via this link.

 

Now let’s dive into the example above:

  • OrbitControls allows the camera to orbit around a target. 
  • The hook named useGLTF is used to load 3d content.

 

I guess you must be wondering how to make a model based on .gltf file. It is so easy if you are using React to create your app by using the syntax

 

npx gltfjsx Lamp.gltf

 

As soon as you enter the syntax, it will create a file named Lamp.js. The only thing you need to do now is copy and paste it into the function Model (so easy right haha).

 

Here is the result 

 

5) Conclusion

Thanks for reading. There’s a lot more that could be said about three.js, but I hope this post has given you enough knowledge to get started with this powerful technology.

If you have any questions feel free to let me know via [email protected]


Resources

References

career_saigon_technology

Ho Chi Minh (Headquater)

location_pin

2nd & 3rd Floor, M.I.D Building, 02 Nguyen The Loc Street, Ward 12 Tan Binh District, Ho Chi Minh City, Vietnam

DMCA.com Protection Status

Quick Links

Opening Jobs

About us

Life at saigontechnology

Blog

Contact Us

PRIVACY POLICY

Follow Us

saigontechnology-great-plage-to-work-partner
saigontechnology-microsoft-partner
iso_9001iso_27001
sao_khue
50_leading

© Copyright 2022 by STS Software Technology JSC, Leading Software Outsourcing Company in Vietnam. All Rights Reserved.