Three.js is a popular JavaScript library used for creating 3D graphics directly in the browser. In this project, we’ll build a 3D rotating cube with lighting and materials to understand how to use Three.js effectively.
// Set up the scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
800 / 600,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 600);
document.getElementById('scene-container').appendChild(renderer.domElement);
// Add orbit controls for interactive camera rotation
const controls = new THREE.OrbitControls(camera, renderer.domElement);
// Create a box geometry and basic material
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshStandardMaterial({ color: 0x44aa88 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Add lighting to the scene
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 5, 5).normalize();
scene.add(light);
// Position the camera
camera.position.z = 5;
// Animation loop to rotate the cube and render the scene
function animate() {
requestAnimationFrame(animate);
// Rotate the cube
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// Update orbit controls
controls.update();
// Render the scene
renderer.render(scene, camera);
}
// Start the animation loop
animate();
Step 5: Run the Project
Open the index.html file in your browser.
You’ll see a 3D rotating cube that you can interact with by dragging with your mouse (thanks to the OrbitControls).
Explanation
Scene, Camera, and Renderer Setup:
The scene is where all objects are placed.
The camera defines the view of the scene.
The renderer renders the scene using WebGL.
Geometry and Materials:
We created a BoxGeometry (the cube).
MeshStandardMaterial gives it a realistic material appearance with lighting.
Lighting:
We added DirectionalLight to illuminate the cube, giving it depth.
Orbit Controls:
The OrbitControls allow the user to rotate the camera interactively with the mouse.
Animation Loop:
We use requestAnimationFrame() to rotate the cube and render the scene continuously for smooth animations.
Possible Enhancements
Add more shapes: Try adding spheres, cones, or custom models.
Change materials: Use MeshLambertMaterial or MeshPhongMaterial for different effects.
Add textures: Apply images as textures on the cube’s faces.
Introduce a skybox: Create a background with a panoramic view.
Physics: Integrate a physics engine like Cannon.js for realistic movements.
Conclusion
This project demonstrates the basics of 3D graphics using Three.js. You’ve created a rotating cube, added lighting, and allowed interactive camera control. Three.js opens up endless possibilities—from simple 3D objects to complex scenes with realistic lighting and physics.
Let me know if you want to add more features or build other exciting 3D projects!