Introduction to Three.js
Three.js is a powerful JavaScript library that simplifies the creation of 3D graphics in web browsers. It provides an abstraction layer over WebGL, making it easier for developers to create complex 3D scenes without dealing directly with low-level graphics programming.
Key Features
Getting Started
First, let's set up a basic Three.js scene. You'll need to include the Three.js library in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>Here's a basic example to create a rotating cube:
// Initialize scene, camera, and renderer
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);
// Create a cube
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;
// Animation loop
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();Working with Materials
Three.js offers various materials for different visual effects:
// Basic material
const basicMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
// Phong material for shiny surfaces
const phongMaterial = new THREE.MeshPhongMaterial({
color: 0xff0000,
shininess: 100,
specular: 0x444444
});
// Standard material for physically based rendering
const standardMaterial = new THREE.MeshStandardMaterial({
color: 0xff0000,
roughness: 0.5,
metalness: 0.5
});Lighting
Adding lights to your scene:
// Ambient light
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
// Directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// Point light
const pointLight = new THREE.PointLight(0xffffff, 1, 100);
pointLight.position.set(10, 10, 10);
scene.add(pointLight);Handling User Input
Implementing orbit controls for user interaction:
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}Loading 3D Models
Three.js supports various 3D model formats. Here's an example using the GLTFLoader:
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
const loader = new GLTFLoader();
loader.load(
'path/to/model.gltf',
function (gltf) {
scene.add(gltf.scene);
},
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function (error) {
console.error('An error occurred:', error);
}
);Performance Optimization
Some key tips for optimizing Three.js applications:
Conclusion
Three.js is a versatile library that makes 3D web graphics accessible to web developers. While we've covered the basics here, there's much more to explore, including advanced features like post-processing effects, custom shaders, and physics integration.
Remember to check the official Three.js documentation and examples for more detailed information and advanced techniques.
