Skip to main content

Archive

Show more

Basic Shapes and Geometry in Three.js

Basic Shapes and Geometry in Three.js

In Three.js, you can create various basic shapes and geometries to build 3D objects in your scene. These shapes serve as the foundation for more complex models and can be customized with different parameters.


1. Creating Basic Shapes

Three.js provides constructors for creating several basic shapes, including:

  • BoxGeometry: A rectangular box.
  • SphereGeometry: A sphere.
  • CylinderGeometry: A cylinder.
  • ConeGeometry: A cone.
  • TorusGeometry: A torus.
  • PlaneGeometry: A plane.

These constructors allow you to define the size, segments, and other properties of the shapes.


2. Example: Creating a Box

Here's an example of creating a simple box geometry in Three.js:

// Create a box geometry
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);

// Create a mesh with the box geometry and a basic material
const boxMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const boxMesh = new THREE.Mesh(boxGeometry, boxMaterial);

// Add the box mesh to the scene
scene.add(boxMesh);

In this example, we create a box geometry with dimensions of 1x1x1. We then create a mesh using the box geometry and a basic material with a green color. Finally, we add the box mesh to the scene.


3. Customizing Geometries

You can customize the geometries by adjusting parameters such as width, height, depth, radius, and segments. Additionally, you can apply textures, colors, and materials to the shapes to create visually appealing objects.

Here's an example of creating a sphere with a custom radius and segments:

// Create a sphere geometry
const sphereGeometry = new THREE.SphereGeometry(0.5, 32, 32);

// Create a mesh with the sphere geometry and a Lambert material
const sphereMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 });
const sphereMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);

// Add the sphere mesh to the scene
scene.add(sphereMesh);

In this example, we create a sphere geometry with a radius of 0.5 and 32 segments along both the horizontal and vertical axes. We then create a mesh using the sphere geometry and a Lambert material with a red color. Finally, we add the sphere mesh to the scene.

By creating and customizing basic shapes and geometries in Three.js, you can build a variety of 3D objects and scenes for your web applications.

Comments