Three.js is the most popular 3D library for the web, but most developers only scratch the surface. Here are the powerful APIs hidden inside.
Scene Setup in 10 Lines
import * as THREE from "three";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 5, 5);
scene.add(light);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
Raycasting (Click Detection in 3D)
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
window.addEventListener("click", (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
intersects[0].object.material.color.set(0xff0000);
}
});
Post-Processing
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass";
import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass";
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
composer.addPass(new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85));
function animate() {
requestAnimationFrame(animate);
composer.render();
}
GLTF Model Loading
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
const loader = new GLTFLoader();
loader.load("/model.glb", (gltf) => {
scene.add(gltf.scene);
gltf.animations.forEach((clip) => {
const mixer = new THREE.AnimationMixer(gltf.scene);
mixer.clipAction(clip).play();
});
});
Key Features
- WebGL renderer with physically-based materials
- Raycasting for 3D interaction
- Post-processing pipeline
- GLTF/GLB model loading with animations
- VR/AR support via WebXR
Need to scrape or monitor web data at scale? Check out my web scraping actors on Apify — ready-made tools that extract data from any website in minutes. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)