Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Threejs

Learn Threejs - 9 Code Examples & CST Typing Practice Test

Three.js is a popular open-source 3D JavaScript library that simplifies creating, displaying, and animating 3D graphics in web browsers using WebGL. It provides abstractions for cameras, lights, materials, geometries, and scene management, making 3D web development accessible and efficient.

View all 9 Threejs code examples →
Simple Three.js SceneThree.js Colored CubeThree.js Plane with TextureThree.js Sphere SceneThree.js Rotating TorusThree.js Orbit Controls ExampleThree.js Point Light SceneThree.js Multiple ObjectsThree.js Animated Spheres

Learn THREEJS with Real Code Examples

Updated Nov 26, 2025

Explain

Three.js abstracts WebGL’s low-level API into an easy-to-use framework for 3D graphics.

It supports cameras, lights, meshes, materials, textures, and animations.

Offers utilities for loading 3D models (GLTF, OBJ, FBX) and textures.

Provides helpers for physics, particles, post-processing, and shaders.

Runs natively in browsers without plugins via WebGL.

Core Features

Scene graph management

Cameras, lights, and shadows

Meshes, geometries, and materials

Loaders for 3D models and textures

ShaderMaterial for custom GLSL shaders

Basic Concepts Overview

Scene -> container for 3D objects

Camera -> defines perspective or orthographic view

Renderer -> draws the scene using WebGL

Meshes -> combination of geometry and material

Lights -> illuminate objects in the scene

Project Structure

index.html - HTML container with canvas

main.js - initializes Three.js scene and renderer

models/ - GLTF/OBJ 3D assets

textures/ - image assets for materials

utils/ - helper functions for scene management

Building Workflow

Set up scene, camera, and renderer

Create geometries, materials, and meshes

Add objects to scene

Add lights and shadows

Animate and render using requestAnimationFrame

Difficulty Use Cases

Beginner: display a spinning cube

Intermediate: load 3D models and textures

Advanced: implement post-processing and shaders

Expert: WebXR-enabled VR/AR experiences

Architect: full 3D web application with animations and interactions

Comparisons

Three.js vs raw WebGL: easier to use, less control

Three.js vs Babylon.js: simpler API, smaller bundle

Three.js vs WebGPU: less low-level control, slower for heavy compute

Three.js vs Unity WebGL: more lightweight, JS-based

Three.js vs PlayCanvas: open-source vs SaaS engine

Versioning Timeline

2010 - Three.js created by Ricardo Cabello

2011-2015 - Core development and feature expansion

2016 - GLTF support and loaders added

2018 - WebXR support introduced

2023 - Latest stable release with enhanced materials and performance

Glossary

Scene - container for 3D objects

Camera - viewpoint for rendering

Renderer - renders scene using WebGL

Mesh - geometry + material

Material - defines appearance of mesh

Installation Setup

Include via npm (`npm install three`) or CDN

Import core classes (Scene, Camera, Renderer, etc.)

Create a scene and camera

Initialize WebGLRenderer and attach to canvas

Add objects, lights, and start animation loop

Environment Setup

Modern browser with WebGL support

Node.js for local development

Bundler like Vite, Webpack, or Parcel

Access to 3D models and textures

Optional: WebXR-capable device

Config Files

index.html - canvas and script

main.js - Three.js scene setup

models/ - 3D assets

textures/ - image files

utils/ - helper functions

Cli Commands

npm install three

vite dev / webpack dev

npm run build

npx serve to host locally

Use Three.js editor for scene prototyping

Internationalization

Three.js is language-agnostic

Text overlays handled by JS/HTML

Localization independent of 3D rendering

Model/texture content may need translation

Number/date formatting in UI handled separately

Accessibility

Provide alternative text for canvas

Keyboard navigation for interactions

Consider motion sensitivity for animations

Screen readers interact with HTML UI

Three.js does not handle accessibility directly

Ui Styling

Handled in HTML/CSS for overlays

Canvas displays 3D content

Responsive layout adjusts canvas size

Interaction handled via JS events

Three.js only manages rendering, not UI

State Management

Scene stores object hierarchy

Meshes maintain local transforms

Animation mixer updates object state

Camera controls user viewpoint

Renderer draws current state each frame

Data Management

Load models and textures efficiently

Reuse geometries and materials

Minimize draw calls for performance

Use instancing for repeated objects

Optimize texture resolution and compression

Architecture

Scene -> hierarchical structure of objects

Camera -> viewpoint for rendering

Renderer -> WebGL renderer that draws the scene

Meshes -> geometry + material combinations

Animation loop -> requestAnimationFrame-driven render loop

Rendering Model

Scene graph defines objects hierarchy

Renderer draws scene using WebGL

Camera defines viewpoint

Animation loop updates scene per frame

Lights and materials define final appearance

Architectural Patterns

Scene-graph-based rendering

Animation loop with requestAnimationFrame

Component-based mesh/material system

Event-driven input handling

Plugin system for loaders and effects

Real World Architectures

Web-based 3D games

AR/VR interactive experiences

Product configurators

Scientific and architectural visualizations

Marketing and interactive websites

Design Principles

Ease of use over low-level control

Cross-browser compatibility

Flexible and extensible API

Active community-driven development

Lightweight but feature-rich

Scalability Guide

Use instanced meshes for repeated objects

Optimize geometry and texture sizes

Batch animations and updates

Use LOD (level-of-detail) techniques

Split scene into manageable chunks

Migration Guide

Convert raw WebGL code to Three.js abstractions

Use loaders instead of manual geometry setup

Replace custom shaders with ShaderMaterial if needed

Move animation logic into Three.js mixers

Adopt scene graph for object hierarchy

Performance Notes

Use BufferGeometry for large models

Limit draw calls by merging meshes

Reduce texture resolution if needed

Use frustum culling

Reuse materials and geometries

Security Notes

Runs sandboxed in browser

No unsafe memory access

Avoid loading untrusted assets

WebGL shaders validated by browser

No direct access to GPU beyond WebGL API

Monitoring Analytics

Use Stats.js for FPS monitoring

Profile renderer for bottlenecks

Track texture and memory usage

Test performance across devices

Log animation timings and user interactions

Code Quality

Reuse materials and geometries

Keep scene graph organized

Use helper functions for repetitive tasks

Modularize shaders and animations

Follow naming conventions for objects

Practical Examples

Simple rotating cube

GLTF model loading and rendering

Particle systems

Physics-enabled 3D simulations

AR/VR interactive scene via WebXR

Troubleshooting

Check console for WebGL errors

Ensure model paths are correct

Verify textures are loaded

Update renderer size on window resize

Enable shadows and lights correctly

Testing Guide

Test scene performance in different browsers

Use Stats.js to measure FPS

Validate shader compilation

Check model and texture loading

Use dev tools for memory profiling

Deployment Options

Static hosting (Netlify, Vercel)

CDN for assets

Integration with React/Next.js

Use Webpack/Vite for bundling

Progressive enhancement for mobile devices

Tools Ecosystem

Three.js Editor - browser-based scene editor

GLTFLoader/OBJLoader - model loaders

Postprocessing library

three-stdlib - utilities and helpers

ShaderMaterial for custom GLSL effects

Integrations

WebXR for VR/AR

Cannon.js, Ammo.js for physics

GSAP for animation control

React Three Fiber for React integration

Troika-3D text rendering

Productivity Tips

Reuse meshes and materials

Use helper libraries for loaders and controls

Keep animations modular

Profile performance regularly

Use the Three.js editor for prototyping

Challenges

Managing complex scenes

Shader programming for custom effects

Optimizing performance for large models

Synchronizing physics and animation

Cross-browser and mobile compatibility

Learning Path

Learn basics of WebGL concepts

Understand Three.js core classes (Scene, Camera, Renderer)

Create simple objects and materials

Animate scenes and load 3D models

Build complex interactive 3D applications

Skill Improvement Plan

Week 1: Geometry and materials

Week 2: Lights, shadows, and cameras

Week 3: Model loading and textures

Week 4: Animation and post-processing

Week 5: WebXR and physics integration

Interview Questions

Explain Three.js scene graph architecture.

How do you implement shadows in Three.js?

What is the difference between MeshBasicMaterial and MeshStandardMaterial?

How to load and animate a GLTF model?

Describe the rendering loop using requestAnimationFrame.

Cheat Sheet

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera();

const renderer = new THREE.WebGLRenderer();

const mesh = new THREE.Mesh(geometry, material);

renderer.render(scene, camera);

Books

Learning Three.js - The JavaScript 3D Library

Three.js Cookbook

Three.js Essentials

Mastering Three.js

Three.js Animation Techniques

Tutorials

Three.js fundamentals

Loading 3D models with Three.js

Animating objects and cameras

Post-processing effects

WebXR experiences with Three.js

Official Docs

https://threejs.org/docs/

https://threejs.org/

Community Links

Three.js GitHub

Three.js Slack and Discord

StackOverflow Three.js tag

Reddit r/threejs

YouTube Three.js tutorials

Community Support

Three.js GitHub repository

Three.js Slack and Discord channels

StackOverflow Three.js tag

Reddit r/threejs

Various tutorials and YouTube channels

Monetization

3D product configurators for e-commerce

Interactive marketing campaigns

Web-based 3D games and experiences

AR/VR training platforms

Premium 3D visualization SaaS

Future Roadmap

Better WebGPU integration

Enhanced post-processing and PBR

Improved model loaders and exporters

WebXR AR/VR enhancements

More community-driven extensions and plugins

When Not To Use

Heavy GPU compute tasks -> use WebGPU

Ultra-realistic AAA game -> use Unity/Unreal

Simple 2D canvas -> use Canvas2D

Non-browser environments

If team prefers visual editors over code

Final Summary

Three.js simplifies web-based 3D graphics development.

Abstraction over WebGL makes it beginner-friendly.

Supports models, textures, animations, and effects.

Widely used in games, AR/VR, visualization, and interactive websites.

Foundation for web 3D experiences.

Faq

Is Three.js free? -> Yes, MIT licensed.

Does it work on mobile? -> Yes, with WebGL support.

Can Three.js use WebGPU? -> Experimental via renderer.

Do I need to know WebGL? -> Helpful but not mandatory.

Is Three.js good for games? -> Suitable for browser-based 3D games.

Code Sample Descriptions

1

Simple Three.js Scene

# threejs/demo/main.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
}
animate();

A basic Three.js program that renders a spinning cube in a browser canvas.

Let’s Try →
2

Three.js Colored Cube

# threejs/demo/colored_cube.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.BoxGeometry();
const materials = [
    new THREE.MeshBasicMaterial({color: 0xff0000}),
    new THREE.MeshBasicMaterial({color: 0x00ff00}),
    new THREE.MeshBasicMaterial({color: 0x0000ff}),
    new THREE.MeshBasicMaterial({color: 0xffff00}),
    new THREE.MeshBasicMaterial({color: 0xff00ff}),
    new THREE.MeshBasicMaterial({color: 0x00ffff})
];
const cube = new THREE.Mesh(geometry, materials);
scene.add(cube);
camera.position.z = 5;
function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
}
animate();

A cube with different face colors rendered in Three.js.

Let’s Try →
3

Three.js Plane with Texture

# threejs/demo/texture_plane.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.PlaneGeometry(5, 5);
const texture = new THREE.TextureLoader().load('texture.jpg');
const material = new THREE.MeshBasicMaterial({ map: texture });
const plane = new THREE.Mesh(geometry, material);
scene.add(plane);
camera.position.z = 5;
renderer.render(scene, camera);

Displays a textured plane in Three.js.

Let’s Try →
4

Three.js Sphere Scene

# threejs/demo/sphere.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.SphereGeometry(1, 32, 32);
const material = new THREE.MeshBasicMaterial({ color: 0x0077ff });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
camera.position.z = 5;
renderer.render(scene, camera);

Renders a sphere in Three.js.

Let’s Try →
5

Three.js Rotating Torus

# threejs/demo/torus.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.TorusGeometry(1, 0.4, 16, 100);
const material = new THREE.MeshBasicMaterial({ color: 0xff6600 });
const torus = new THREE.Mesh(geometry, material);
scene.add(torus);
camera.position.z = 5;
function animate() {
    requestAnimationFrame(animate);
    torus.rotation.x += 0.01;
    torus.rotation.y += 0.01;
    renderer.render(scene, camera);
}
animate();

Creates a rotating torus shape in Three.js.

Let’s Try →
6

Three.js Orbit Controls Example

# threejs/demo/orbit_controls.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
camera.position.z = 5;
function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
}
animate();

Uses OrbitControls to allow interactive camera rotation.

Let’s Try →
7

Three.js Point Light Scene

# threejs/demo/point_light.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
const pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(5,5,5);
scene.add(pointLight);
camera.position.z = 5;
function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
}
animate();

Adds a point light to illuminate a cube.

Let’s Try →
8

Three.js Multiple Objects

# threejs/demo/multiple_cubes.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const colors = [0xff0000, 0x00ff00, 0x0000ff];
for(let i=0;i<3;i++){
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({ color: colors[i] });
    const cube = new THREE.Mesh(geometry, material);
    cube.position.x = (i-1)*2;
    scene.add(cube);
}
camera.position.z = 5;
renderer.render(scene, camera);

Renders multiple cubes in the scene with different colors.

Let’s Try →
9

Three.js Animated Spheres

# threejs/demo/animated_spheres.js
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
renderer.setSize(window.innerWidth, window.innerHeight);
const spheres = [];
for(let i=0;i<3;i++){
    const geometry = new THREE.SphereGeometry(0.5,32,32);
    const material = new THREE.MeshBasicMaterial({color: 0xff00ff});
    const sphere = new THREE.Mesh(geometry, material);
    sphere.position.x = (i-1)*2;
    scene.add(sphere);
    spheres.push(sphere);
}
camera.position.z = 5;
let t=0;
function animate(){
    t+=0.05;
    spheres.forEach((s,i)=>{ s.position.y = Math.sin(t+i); });
    requestAnimationFrame(animate);
    renderer.render(scene,camera);
}
animate();

Creates multiple spheres that bounce up and down.

Let’s Try →

Frequently Asked Questions about Threejs

What is Threejs?

Three.js is a popular open-source 3D JavaScript library that simplifies creating, displaying, and animating 3D graphics in web browsers using WebGL. It provides abstractions for cameras, lights, materials, geometries, and scene management, making 3D web development accessible and efficient.

What are the primary use cases for Threejs?

Interactive 3D websites and apps. Product visualization and configurators. Web-based games using WebGL. AR/VR experiences via WebXR. Scientific and architectural visualizations

What are the strengths of Threejs?

Simplifies WebGL 3D rendering. Large ecosystem with plugins and examples. Flexible and extensible. Active community support. Good performance for real-time 3D web apps

What are the limitations of Threejs?

Not as low-level as raw WebGL or WebGPU. Performance bottlenecks with very large scenes. Limited compute capabilities (no native GPU compute). Some advanced effects require custom shaders. Debugging can be challenging for complex scenes

How can I practice Threejs typing speed?

CodeSpeedTest offers 9+ real Threejs code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.