DEV Community

Tianya School
Tianya School

Posted on

WebGL and Three.js-3D Graphics Applications on the Web

WebGL (Web Graphics Library) is a JavaScript API that enables hardware-accelerated 3D graphics rendering in any compatible web browser without the need for plugins. Based on the OpenGL standard, it integrates directly with HTML5’s Canvas element. WebGL allows developers to create complex 3D visual effects on web pages.

Three.js is a popular JavaScript library that encapsulates the complexity of WebGL, providing a more user-friendly interface for creating 3D content. It simplifies low-level WebGL tasks such as vertex buffer management, shader handling, and texture loading, allowing developers to focus on building 3D scenes and interactions.

Basic Steps for Creating a 3D Scene with Three.js

1. Set Up the HTML Structure

<!DOCTYPE html> <html> <head> <title>Three.js Scene</title> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r137/three.min.js"></script> <script> // JavaScript code will go here </script> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

This includes the Three.js library via a CDN link.

2. Initialize Scene, Camera, and Renderer

const scene = new THREE.Scene(); // Create a scene const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // Create a perspective camera const renderer = new THREE.WebGLRenderer(); // Create a renderer renderer.setSize(window.innerWidth, window.innerHeight); // Set renderer size document.body.appendChild(renderer.domElement); // Add renderer output to the page 
Enter fullscreen mode Exit fullscreen mode

The Scene is a container for all 3D objects, the Camera defines the viewpoint of the 3D world, and the Renderer is responsible for rendering the scene to the screen.

3. Create 3D Objects

const geometry = new THREE.BoxGeometry(1, 1, 1); // Create a cube geometry const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // Create a basic material, colored green const cube = new THREE.Mesh(geometry, material); // Create a mesh combining geometry and material scene.add(cube); // Add to the scene 
Enter fullscreen mode Exit fullscreen mode

This creates a basic cube mesh object.

4. Animation Loop

function animate() { requestAnimationFrame(animate); // Use requestAnimationFrame for per-frame updates cube.rotation.x += 0.01; // Update cube rotation cube.rotation.y += 0.01; renderer.render(scene, camera); // Render the scene } animate(); // Start the animation 
Enter fullscreen mode Exit fullscreen mode

The animation loop uses requestAnimationFrame to update the cube’s rotation and re-render the scene each frame.

5. Lighting and Shaders

Three.js supports various light sources and custom shaders, enabling complex lighting effects and custom surface appearances for 3D objects.

6. Interactivity

Interactivity with 3D objects, such as dragging, scaling, or rotating, can be implemented by listening to mouse and touch events.

7. Textures and Materials

Textures can be added to 3D objects by loading image files, enhancing visual realism.

8. Loading 3D Models

Three.js supports loading external 3D model files in formats like .obj, .gltf, and others.

9. Animation and Keyframes

  • THREE.AnimationMixer: Used to create complex animation sequences by controlling 3D object properties via keyframes.
  • THREE.KeyframeTrack: Defines property values at specific time points.
  • THREE.AnimationClip: Combines multiple keyframe tracks into a complete animation segment.

10. Camera Controllers

Three.js provides camera controllers like OrbitControls and FirstPersonControls, facilitating user-controlled panning, rotation, and zooming in 3D space.

11. Lighting System

  • THREE.PointLight, THREE.DirectionalLight, THREE.SpotLight, and THREE.AmbientLight represent point lights, directional lights, spotlights, and ambient lights, respectively.
  • THREE.LightShadow enables shadow effects for light sources.

12. Particle Systems

  • THREE.ParticleSystem and THREE.Points create particle effects like smoke, sparks, or raindrops.
  • Combined with THREE.Geometry and THREE.PointsMaterial, particle shapes and appearances can be customized.

13. Texture Mapping

  • THREE.TextureLoader: Loads texture images.
  • THREE.CubeTextureLoader: Loads cube maps, commonly used for environment mapping.
  • THREE.VideoTexture: Uses video as a texture for 3D objects.

14. Geometries

In addition to basic geometries (e.g., BoxGeometry, SphereGeometry), Three.js supports creating complex shapes like toruses, cylinders, and cones. The THREE.Geometry.merge() method allows combining multiple geometries.

15. Physics Engine Integration

Third-party libraries like Cannon.js or Ammo.js can integrate physics simulations (e.g., collision detection, gravity) into Three.js scenes.

16. Custom Shaders

Three.js supports GLSL (OpenGL Shading Language) shaders, allowing developers to write custom vertex and fragment shaders for complex lighting and surface effects.

17. WebVR and WebXR

For virtual reality (VR) and augmented reality (AR), Three.js provides WebVRManager and WebXRManager to create immersive experiences on compatible devices.

Example: Creating a 3D Application with Three.js

Here’s a complete example of a 3D cube application using Three.js, including scene setup, camera, renderer, geometry, material, and animation loop:

<!DOCTYPE html> <html> <head> <title>Three.js Cube Example</title> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r137/three.min.js"></script> <script> // Create scene const scene = new THREE.Scene(); // Create camera const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; // Create renderer const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // Create cube const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); const cube = new THREE.Mesh(geometry, material); scene.add(cube); // Animation loop function animate() { requestAnimationFrame(animate); cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render(scene, camera); } animate(); </script> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

Code Breakdown:

  1. Include Three.js Library: The latest Three.js version (v0.137.0) is included via CDN.
  2. Create Scene, Camera, and Renderer:
    • THREE.Scene: The container for all 3D objects.
    • THREE.PerspectiveCamera: Creates a perspective camera with parameters for field of view, aspect ratio, near clipping plane, and far clipping plane.
    • THREE.WebGLRenderer: Sets up the renderer, configures its size, and adds it to the HTML page.
  3. Create Cube:
    • THREE.BoxGeometry: Creates a unit cube geometry.
    • THREE.MeshBasicMaterial: Defines a basic material with a green color.
    • THREE.Mesh: Combines geometry and material into a renderable mesh.
  4. Set Camera Position: Moves the camera 5 units along the Z-axis to view the cube from the side.
  5. Animation Loop:
    • requestAnimationFrame(animate): Calls the animate function on the next browser repaint for smooth animations.
    • Updates the cube’s X and Y rotation angles each frame to rotate the cube.
    • renderer.render(scene, camera): Renders the scene using the current camera perspective.

Creating a 3D Application with WebGL

Creating a 3D application with raw WebGL involves multiple steps, including setting up the context, creating geometries, defining materials, configuring the camera, setting up lighting, and implementing a render loop.

<!DOCTYPE html> <html> <head> <title>WebGL Example</title> </head> <body> <canvas id="glCanvas" width="800" height="600"></canvas> <script> // WebGL code will go here const canvas = document.getElementById('glCanvas'); const gl = canvas.getContext('webgl'); if (!gl) { alert('WebGL not supported'); } // Further WebGL setup and rendering logic </script> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

👉 Click to join and systematically improve development capabilities: Advanced Development Learning

Top comments (0)