Reading Notes-Working with the Basic Components That Make Up a Three.js Scene
2 min readFeb 8, 2024
Jos Dirksen, Learning Three.js- The JavaScript 3D Library for WebGL, 2013
Basic Components
1- Scene
2- Camera
- Perspective
- Orthographic
3- Renderer
- WebGL-based(recommend)
- Canvas-based (X recommend, 耗效能)
- SVG-based (X recommend, 耗效能)
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 );
// add the renderer(a <canvas> element) element to our HTML document
document.body.appendChild( renderer.domElement );
renderer.render(scene, camera);
Create a scene
The scene is the main container in the Three.js library
- .add( object : Object3D, …)
- .children — return a list of objects that were added to the scene
- .getChildByName( name: String ) — return an object with a specific name
- .remove( object : Object3D, …)
- .travers ( callback: Function )
- .fog — create 景深效果
- .overrideMaterial
Adding 3D Objects
Working with the Geometry and Mesh objects
1- Geometries
define the shape of an object(形狀)
2- Material
define the material of an object(材質)
3- Mesh
which Three.js can render and will combine many geometries
M.position.set()
M.position = new THREE.Vector3(x, y, z)
M.rotation.set(x, y, z)
M.rotation = new THREE.Vector3(x, y, z)
M.rotation.x = 0.5 * Math.PI
.translateX() / .translateY() / .translateZ(): move Mesh
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
Mesh is relative to its parent object (也就是 Scene)
Using the available cameras for different uses
- specific point
position(0, 0, 0)
: pointed to the center of the scenecamera.lookAt(new THREE.Vector3(x, y, z))
Perspective
the further away, the smaller they render. e.g. game (real world-like)
Orthographic
render same size (不考慮距離) e.g. goole map