Building Interactive 3D Viewers with Three.js and Angular
star Featured

Building Interactive 3D Viewers with Three.js and Angular

Step-by-step guide to integrating Three.js with Angular for creating stunning interactive 3D visualizations.

Three.js is a JavaScript 3D library that makes WebGL much more accessible. Combined with Angular, you can create powerful 3D experiences.

Getting Started with Three.js

First, install Three.js:

npm install three

npm install --save-dev @types/three

Basic Setup

Create a component with a canvas element:

@Component({

selector: 'app-3d-viewer',

template: '<canvas #canvas></canvas>'

})

export class Viewer3D implements AfterViewInit {

@ViewChild('canvas') canvas!: ElementRef<HTMLCanvasElement>;

}

Initializing the Scene

In Angular 20 using signals and inject:

const canvas = viewChild<ElementRef>('canvas');

private renderer: THREE.WebGLRenderer | null = null;

private scene: THREE.Scene | null = null;

private camera: THREE.PerspectiveCamera | null = null;

ngAfterViewInit() {

const canvasElement = this.canvas()?.nativeElement;

if (!canvasElement) return;

this.scene = new THREE.Scene();

this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

this.renderer = new THREE.WebGLRenderer({ canvas: canvasElement, antialias: true });

}

Adding Lights

Lights are crucial for realistic 3D rendering:

const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);

this.scene!.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);

directionalLight.position.set(5, 10, 7);

this.scene!.add(directionalLight);

Loading Models

Use GLTFLoader for 3D models:

const loader = new GLTFLoader();

loader.load('/models/model.gltf', (gltf) => {

this.model = gltf.scene;

this.scene!.add(this.model);

});

Animation Loop

Render continuously:

render() {

requestAnimationFrame(() => this.render());

this.model!.rotation.y += 0.005;

this.renderer!.render(this.scene!, this.camera!);

}

Interactivity with OrbitControls

Allow users to interact with the scene:

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

const controls = new OrbitControls(this.camera, this.renderer!.domElement);

controls.enableDamping = true;

controls.autoRotate = true;

Performance Considerations

  1. Use LOD (Level of Detail) for complex models
  2. Dispose of geometries and materials when not needed
  3. Use WebWorkers for heavy computations
  4. Optimize textures (size and format)
  5. Consider using InstancedMesh for many repeated objects

SSR Compatibility

Handle server-side rendering:

const isBrowser = isPlatformBrowser(this.platformId);

if (isBrowser) {

this.initializeThreeJS();

}

Conclusion

Three.js with Angular provides a powerful combination for 3D web applications. Start simple with basic geometries and gradually add complexity as you learn.