Overview
Three.js revolves around geometry, which defines the shape and structure of 3D objects in your scenes. In this article, we will take an in-depth look at geometry in Three.js, covering the basics, common types of geometries, how to create custom geometries, and applying materials for stunning visualizations.
What is Geometry in Three.js?
In Three.js, geometry represents the physical form of 3D objects. It defines the vertices, edges, and faces that compose an object, providing the foundation of rendering and interaction. Geometries are the building blocks of 3D scenes, enabling you to create everything from simple cubes to complex architectural models and intricate organic shapes.
Basic Geometries in Three.js
Three.js comes with several built-in geometries that make it easy to create common 3D shapes:
BoxGeometry:
This geometry generates a cube or rectangular prism. You can specify its width, height and depth.
SphereGeometry:
Create spherical objects like planets or balls. You can set the radius and choose the number of segments and rings for more or fewer vertices.
CylinderGeometry:
Construct cylinders with varying radii, heights, and segments counts. It's perfect for creating anything from soda cans to tree trunks.
PlaneGeometry:
This generates flat surfaces, which are often used for floors, walls, or tabletops. You can control its size and subdivisions.
TorusGeometry:
Produce doughnut-shaped objects knwon as tori. Customize the major and minor radii and choose the number of segments and radial segments.
Custom Geometries:
You can create your own custom geometries by specifying the vertices and faces manually. This allows for limitless creativity, enabling you to craft unique shapes that suits your project's needs.
Creating and Using Geometries
To use geometries in Three.js, follow these steps:
Create a Geometry
Instantiate a geometry, specifying its parameters. For example, to create a sphere, you can use the following code:
const sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
Create a Mesh
A mesh is a visual representation of a geometry combined with a material. To create a mesh, you need both a geometry and a material:
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const sphereMesh = new THREE.Mesh(sphereGeometry, material);
Adding to Scene
Finally, add the mesh to your 3D scene:
scene.add(sphereMesh);
Position and Transform
You can position, rotate, and scale the mesh as needed to fit your scene.