DJC1 - Day 17 - Reaching One Million Active Users
How to Create Your First 3D Cube with Three.js?
Turn lines of code into three-dimensional shapes: your first 3D cube is just a few steps away.
Three.js is a JavaScript library that allows you to create interactive 3D graphics in the browser easily and efficiently. Creating your first cube is a perfect way to start understanding the basics of 3D modeling and visualization on the web.
To create a basic cube, you need three main elements: scene, camera, and renderer. The scene (Scene) is the container where all 3D objects are placed. The camera (PerspectiveCamera) defines the perspective from which the scene will be viewed. The renderer (WebGLRenderer) is responsible for drawing everything on the browser canvas.
A basic example to create a cube would be:
// 1. Create the scene
const scene = new THREE.Scene();
// 2. Set up the camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
// 3. Set up the renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 4. Create the cube geometry and material
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
// 5. Add the cube to the scene
scene.add(cube);
// 6. Create the animation
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
With this code, you will have a rotating 3D cube in your browser. From here, you can explore how to add more objects, lights, textures, and interactive controls to make more complex and dynamic scenes. Three.js also allows you to integrate external 3D models, particle effects, and advanced animations, making it a very powerful tool for web developers looking to take their projects to the next level.
Versions
v0.1.0
- How to create your first 3D cube with Three.js?