All answers · Motion and code · 55 questions

Three.js and WebGL, answered.

This page answers the questions people ask when they add a live 3D scene, shader background or particle field to a website. It is for designers, developers and AI builders who want 3D that loads fast, works on phones and does not hurt search.

What is three.js?

Three.js is a free, open source JavaScript library that draws 3D graphics in the browser on top of WebGL, and more recently WebGPU. It gives you a scene, cameras, lights, materials, meshes and loaders, so you do not write raw graphics API calls. Most 3D hero sections, product viewers and particle backgrounds on the web are built with three.js or with React Three Fiber, which wraps three.js for React.

Add three.js to a websiteThree.js templates

What is WebGL?

WebGL is the browser API that lets JavaScript use the graphics card to draw 2D and 3D graphics inside a canvas element. WebGL 1 is based on OpenGL ES 2.0 and WebGL 2 on OpenGL ES 3.0, and WebGL 2 is available in all current major browsers. You write shaders in GLSL that run on the GPU. Libraries such as three.js hide most of the low-level setup.

WebGL templatesShader templates

How do I add three.js to a website?

Add a canvas, create a WebGLRenderer, a scene, a camera and one mesh, then render inside renderer.setAnimationLoop. A pattern that holds up in production is one canvas fixed behind the page with the real headline, navigation and buttons as normal HTML above it. Cap the pixel ratio at 2, resize the drawing buffer when the canvas size changes, and pause rendering when the tab is hidden.

Add three.js to a websiteThree.js website templates

Can I use three.js without a build step or npm?

Yes. Add an import map, a script of type importmap that maps the name three to a CDN URL of the module build, then use normal import statements in a module script. The import map must appear before any module script that uses it. Pin an exact version in the URL, and load addons such as OrbitControls or GLTFLoader from the same version as the core library.

Add three.js to a websiteHTML and CSS templates

How do I install three.js with npm?

Run npm install three, then import it with import * as THREE from 'three'. Addons such as OrbitControls, GLTFLoader, DRACOLoader and the post-processing passes live under the three/addons/ path, for example import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'. For TypeScript, install @types/three as a dev dependency. Vite, Next.js and other bundlers handle three.js without extra configuration.

Add three.js to a websiteNext.js templates

How do I use three.js in a React app?

Either use React Three Fiber, which lets you write three.js scenes as JSX, or create a plain three.js renderer inside a useEffect hook. With the useEffect route, build the renderer, scene and loop in the effect and return a cleanup function that stops the loop and disposes geometries, materials, textures and the renderer. Without that cleanup, React's development double run leaves extra WebGL contexts behind.

Three.js in React and Next.jsThree.js templates

What is React Three Fiber?

React Three Fiber is a React renderer for three.js, published as @react-three/fiber. You describe a scene with JSX elements such as mesh, boxGeometry and meshStandardMaterial inside a Canvas component, and React manages creation, updates and disposal. The useFrame hook runs code every frame and useThree gives access to the renderer, camera and size. Anything three.js can do, React Three Fiber can do, because it renders real three.js objects.

Three.js and R3F templatesThree.js website templates

What is drei and do I need it with React Three Fiber?

Drei, published as @react-three/drei, is a helper library for React Three Fiber with ready components such as OrbitControls, Environment, useGLTF, Text, Float, ScrollControls and Html. You do not need it, but it saves a lot of code for common jobs like loading models, adding studio lighting or tying the camera to scroll. Import only the helpers you use so your bundle stays smaller.

Three.js templatesScroll 3D templates

How do I use React Three Fiber in Next.js?

Put the Canvas in a client component by adding the "use client" directive at the top of the file, because three.js needs the browser's window and canvas. In the App Router you can also load the scene with next/dynamic and ssr set to false so it never runs on the server. Render the headline and copy as server HTML outside the canvas, so the page has content before the 3D scene loads.

Next.js templatesAdd three.js to a website

Why does three.js throw window is not defined in Next.js?

The error appears because the three.js code ran during server rendering, where window and document do not exist. Move the scene into a client component marked with the "use client" directive, create the renderer inside useEffect, or import the component with next/dynamic and ssr set to false. Avoid touching window at module top level, since imports are evaluated on the server even in client component trees.

Next.js templatesAdd three.js to a website

Should I use plain three.js or React Three Fiber for a website?

Use React Three Fiber if the site is already React or Next.js, and plain three.js for static HTML sites or a single isolated effect. Performance is about the same, because both draw with the same three.js renderer. React Three Fiber gives you components, hooks and the drei helpers. Plain three.js has no framework dependency and is easier to drop into any page. AnimatedWebs build prompts name the stack, so your AI tool writes the matching version.

Three.js templatesThree.js website templates

What is the difference between WebGL and WebGPU?

WebGPU is the newer browser graphics API, designed around modern GPU interfaces such as Vulkan, Metal and Direct3D 12, while WebGL follows the older OpenGL ES model. WebGPU adds compute shaders, lower driver overhead and a shading language called WGSL instead of GLSL. WebGL runs on almost every device today. WebGPU support is newer and still uneven across older phones, browsers and operating systems.

WebGL templatesShader templates

Should I use WebGPU or WebGL for a website today?

For a marketing site, WebGL is still the safer default, because it works on nearly every visitor's device. Choose WebGPU when you need compute shaders or very large particle counts, and keep a WebGL fallback. Three.js offers a WebGPURenderer that can fall back to a WebGL 2 backend when WebGPU is missing, which lets you adopt WebGPU without losing visitors on older browsers.

WebGL templatesParticle templates

Does three.js support WebGPU?

Yes. Three.js ships a WebGPURenderer, imported from three/webgpu, alongside the long-standing WebGLRenderer. It uses TSL, the three.js shading language written in JavaScript, which compiles to WGSL for WebGPU or GLSL for its WebGL 2 fallback. Custom GLSL ShaderMaterial code does not run on WebGPURenderer unchanged, so plan a port if your scene relies on handwritten shaders.

Three.js templatesShader templates

What is a GLSL shader?

A GLSL shader is a small program written in the OpenGL Shading Language that runs on the graphics card. In WebGL every draw needs two: a vertex shader that positions each vertex and a fragment shader that colors each pixel the shape covers. Because the GPU runs them in parallel for thousands of vertices and pixels, shaders can draw liquid gradients, noise fields and glass effects in real time.

Shader templatesWebGL templates

What is the difference between a vertex shader and a fragment shader?

A vertex shader runs once per vertex and outputs its position on screen through gl_Position, so it can move, bend or wave geometry. A fragment shader runs once per pixel fragment the geometry covers and outputs that pixel's color. The vertex shader can pass values such as UV coordinates to the fragment shader through varyings, which the GPU interpolates across each triangle.

Shader templatesThree.js templates

What are uniforms in GLSL?

Uniforms are values you send from JavaScript to a shader that stay the same for every vertex and pixel in one draw call. Typical uniforms are time, screen resolution, mouse position, scroll progress, colors and textures. In three.js you pass them in the uniforms object of a ShaderMaterial, for example uTime: { value: 0 }, and update material.uniforms.uTime.value each frame to animate the shader.

Shader templatesWebGL templates

What are attributes and varyings in a shader?

Attributes are per-vertex inputs to the vertex shader, such as position, normal and uv, read from the geometry's buffers. Varyings carry values from the vertex shader to the fragment shader, and the GPU interpolates them across each triangle. In GLSL ES 3.00 they are written as in and out instead of attribute and varying. Custom attributes are a cheap way to give each particle its own size, color or random seed.

Shader templatesParticle templates

What is the difference between ShaderMaterial and RawShaderMaterial in three.js?

ShaderMaterial adds three.js built-ins to your shader for you, such as projectionMatrix, modelViewMatrix and the position, normal and uv attributes, so a short custom shader works with little setup. RawShaderMaterial adds nothing, so you declare every uniform, attribute and precision line yourself. Use ShaderMaterial for most effects and RawShaderMaterial when you want full control of the GLSL source.

Shader templatesThree.js templates

How do I make an animated shader background for a website?

Draw one full-screen plane with a fragment shader and feed it a time uniform and a resolution uniform each frame. The fragment shader turns pixel coordinates into color with noise, gradients or distance functions. Put the canvas behind the content with position fixed, keep the fragment code short, cap the pixel ratio, and show a still frame for visitors who prefer reduced motion. AnimatedWebs has 171 animated backgrounds, many built this way.

Shader templatesAnimated backgroundsGradients

Can I make a WebGL background without three.js?

Yes. A shader background needs only raw WebGL: get a context from a canvas, compile a vertex and fragment shader, draw one triangle or quad that covers the screen, and update a time uniform in a requestAnimationFrame loop. The result is a few kilobytes of code instead of a full 3D library. Three.js becomes worth it once you need models, cameras, lights or loaders.

Shader templatesWebGL templates

How do I make particles in three.js?

Create a BufferGeometry with a position attribute holding x, y and z for every particle, then render it with THREE.Points and a PointsMaterial or a custom ShaderMaterial. Move particles in the vertex shader with a time uniform, so the GPU does the work instead of JavaScript updating every point. Use additive blending and a soft round sprite for glowing dust, stars or swarms.

Particle templatesParticle animation templates

How many particles can three.js render smoothly?

Tens of thousands of points run smoothly on most devices when they are animated in a shader, and hundreds of thousands are possible on desktop GPUs. The limit is usually fill rate, not the count: large, overlapping, transparent sprites cost more than many tiny ones. Test on a mid-range phone, lower the count there, and cap the pixel ratio, because every particle pixel is shaded again at high ratios.

Particle templatesFast animation on phones

What is InstancedMesh in three.js?

InstancedMesh draws many copies of the same geometry and material in a single draw call, each with its own transform matrix and optionally its own color. Use it for hundreds or thousands of repeated objects such as cubes, leaves, shards or buildings. Separate meshes would each cost a draw call, which quickly limits frame rate on phones. Update instances with setMatrixAt and set instanceMatrix.needsUpdate to true.

3D object templatesParticle templates

How do I load a GLB model in three.js?

Use GLTFLoader from three/addons/loaders/GLTFLoader.js, call loader.load or await loader.loadAsync with the file URL, and add gltf.scene to your scene. If the file uses Draco geometry compression, attach a DRACOLoader with the decoder path, and for KTX2 textures attach a KTX2Loader. In React Three Fiber, the drei useGLTF hook does the same in one line and caches the result.

3D object templates3D product animation templates

What is the difference between GLB and glTF?

Both are the same glTF 2.0 3D format from the Khronos Group. A .gltf file is JSON that usually points to separate .bin geometry and image texture files, while a .glb file packs everything into one binary file. GLB is the usual choice for websites because it is one request and slightly smaller. Both load with three.js GLTFLoader.

3D object templates3D website templates

What is Draco compression for 3D models?

Draco is an open source library from Google that compresses mesh geometry, often shrinking the geometry part of a glTF file many times over. The browser decodes it with a small WebAssembly or JavaScript decoder, which three.js loads through DRACOLoader. Draco only compresses geometry, not textures, and decoding adds a little CPU time, so it pays off most on dense meshes.

3D object templates3D product animation templates

What is KTX2 texture compression and why use it?

KTX2 with Basis Universal is a texture format that stays compressed in GPU memory, unlike PNG or JPEG, which the browser decompresses to full size. A 2048 by 2048 PNG texture takes about 16 MB of GPU memory uncompressed, more with mipmaps, while a GPU-compressed version takes a fraction of that. Three.js loads it with KTX2Loader, which transcodes to whatever format the device supports. It matters most on phones with limited memory.

3D object templatesFast animation on phones

How do I make a 3D model smaller for the web?

Reduce polygons, resize textures to the size they appear on screen, then compress. The open source glTF Transform command line tool can deduplicate data, simplify meshes, resize textures, convert them to WebP or KTX2 and apply Draco or meshopt compression in one optimize command. Remove hidden geometry and unused animations before export. Check the result in a glTF viewer before shipping.

3D object templatesAdd three.js to a website

How do I add bloom in three.js?

Use EffectComposer with a RenderPass, an UnrealBloomPass and an OutputPass, all from three/addons/postprocessing/, then call composer.render() instead of renderer.render(). Tune strength, radius and threshold so only bright parts glow. In React Three Fiber, the @react-three/postprocessing package offers an EffectComposer with a Bloom effect. Raise emissive intensity above 1 on chosen materials and set a high threshold, so only those objects glow instead of the whole frame.

Shader templatesThree.js templates

Is post-processing expensive on mobile devices?

Yes. Every post-processing pass redraws the full screen at least once, and bloom uses several blurred passes at different sizes, so the cost grows with screen pixels. On phones, render effects at a lower resolution, use fewer passes, and turn bloom off first when frame rate drops. A baked glow in a texture or an additive sprite often looks the same for a fraction of the cost.

Fast animation on phonesPerformance answers

Why should I cap devicePixelRatio in three.js?

A phone with a device pixel ratio of 3 asks the GPU to shade nine times as many pixels as a ratio of 1, which is the most common reason a 3D scene runs badly on phones. Call renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)), or in React Three Fiber set dpr={[1, 2]} on the Canvas. A cap of 1.5 is often indistinguishable on a moving background.

Add three.js to a websiteFast animation on phones

How do I pause a three.js scene when it is off-screen?

Watch the canvas with an IntersectionObserver and call renderer.setAnimationLoop(null) when it leaves the viewport, then restart the loop when it comes back. Also listen for the visibilitychange event so the loop stops when the tab is hidden. Browsers already pause requestAnimationFrame in background tabs, but an observer is what stops a hero scene that has simply scrolled out of view.

Add three.js to a websiteReduced motion and performance

How do I stop React Three Fiber from rendering every frame?

Set frameloop="demand" on the Canvas, and React Three Fiber renders only when props change or when you call invalidate(). That suits product viewers and scenes that move only on interaction, and it saves battery. For a scene that scrolls out of view, set frameloop to never while hidden and back to always when visible, using an IntersectionObserver on the wrapper element.

Three.js templates3D object templates

How do I add a fallback when WebGL is not available?

Test for a context before creating the renderer with canvas.getContext('webgl2') or 'webgl', and show a still poster image if it returns null. Passing failIfMajorPerformanceCaveat: true asks the browser to refuse when it would use a slow software renderer. Keep the headline, copy and buttons in HTML, so the page still works without the canvas. The worst case should be a plain background, not a broken page.

Fast animation on phonesAdd three.js to a website

What happens when a WebGL context is lost?

The browser can take a WebGL context away, for example under memory pressure or after a GPU driver reset, and the canvas stops drawing. Listen for the webglcontextlost event on the canvas, call preventDefault to allow restoration, stop your loop, and show the poster. On webglcontextrestored, recreate resources and restart. Phones lose contexts more often when a page runs several canvases at once.

Add three.js to a websiteFast animation on phones

Why is my three.js scene slow on phones?

The usual causes are an uncapped pixel ratio, heavy fragment shaders, real-time shadows, post-processing passes, large textures and too many draw calls. Phone GPUs have far less fill rate and memory than desktop cards, so cost per pixel matters most. Cap the ratio at 2 or lower, bake lighting into textures, merge or instance meshes, and step quality down when frame times stay high.

Fast animation on phonesPerformance answers

Which three.js materials and lights are cheapest?

MeshBasicMaterial is the cheapest because it ignores lights, followed by MeshLambertMaterial and MeshPhongMaterial. MeshStandardMaterial and MeshPhysicalMaterial look most realistic but cost more per pixel, and transmission renders the scene a second time. Each extra light adds work, and shadow-casting lights add a full extra render. An environment map with one directional light usually looks good at a fair cost.

Three.js templatesAdd three.js to a website

How do I make a three.js canvas transparent over my page?

Create the renderer with new THREE.WebGLRenderer({ alpha: true }) and leave scene.background unset, or call renderer.setClearColor(0x000000, 0). The canvas then shows the page behind it. To put the canvas behind your content, give it position fixed, inset 0 and a negative z-index, and set pointer-events none if it should not catch clicks meant for the HTML above.

Add three.js to a websiteAnimated backgrounds

How many WebGL canvases can one page have?

Browsers cap the number of live WebGL contexts per page, with desktop Chrome allowing 16, and drop the oldest when the cap is passed. Phones can run out of GPU memory well before that. Use one canvas for the whole page where you can, and move a camera through it or fade objects in and out. In React Three Fiber, drei's View component renders several regions from one shared canvas.

Add three.js to a websiteThree.js templates

How do I dispose of three.js objects to avoid memory leaks?

Call dispose() on every geometry, material and texture you created when you remove it, and call renderer.dispose() when the whole scene goes away. Removing a mesh from the scene does not free its GPU memory. In React, do this in the useEffect cleanup function. React Three Fiber disposes objects it created on unmount, but you still dispose textures and render targets you made yourself.

Add three.js to a websiteThree.js templates

How do I build a 3D product viewer for a website?

Load a compressed GLB of the product, light it with an HDR environment map, and add OrbitControls with damping and limits on zoom and vertical angle. Render on demand rather than every frame, so the viewer is idle when nobody touches it. Show a still render as the poster while the model loads. AnimatedWebs 3D object templates cover turntables, configurators and exploded views.

3D object templates3D product animation templates

How do I make an interactive 3D globe for a website?

Use a sphere with an earth or dot texture, or draw the land as points, then convert latitude and longitude to positions on the sphere for markers and arcs. Animate arcs with a shader or a dashed line, add slow auto-rotation, and let OrbitControls handle drag. Open source helpers built on three.js can save time. Keep the dot count modest on phones and pause rotation off-screen.

Three.js templatesParticle templates

How do I move a three.js camera along a path on scroll?

Define the path with a CatmullRomCurve3 through a few points, turn scroll progress into a number between 0 and 1, and set the camera position from curve.getPointAt(progress) inside the render loop. Point the camera at a target or a point slightly ahead on the curve. Store scroll in the scroll handler, and ease toward it in the loop so the camera glides instead of jumping.

Scroll 3D templatesScroll animation guide

Can I use GSAP ScrollTrigger with three.js?

Yes. GSAP can tween any number, including camera positions, rotations and shader uniforms, and ScrollTrigger with scrub ties those tweens to scroll. A common setup pins the canvas section and scrubs a timeline that moves the camera and fades materials. Keep a single render loop and let GSAP only change values. AnimatedWebs has a GSAP animation collection and scroll-driven 3D templates.

GSAP animation templatesScroll 3D templatesGSAP answers

Does three.js hurt SEO?

Three.js does not hurt SEO by itself, but anything drawn only on the canvas is invisible to search engines and screen readers. Keep headlines, copy, links and product details in normal HTML, ideally rendered on the server, and use the canvas as decoration. The bigger risks are slow loading and a blank first screen, so load the 3D code after the first paint and show a poster first.

Add three.js to a websiteWebGL hero ideas

Does a WebGL canvas count toward Largest Contentful Paint?

No. Largest Contentful Paint considers images, video posters and first frames, CSS background images and text blocks, but not canvas drawings. On a page with a 3D hero, the LCP element is usually the headline or a poster image, so make those render fast as plain HTML. Loading three.js still competes for bandwidth and main-thread time, which can delay LCP and hurt Interaction to Next Paint.

Performance answersFast animation on phones

Does three.js slow down page load?

It can. The core library is a few hundred kilobytes of minified JavaScript, plus any models and textures, and parsing it takes main-thread time on phones. Load it with a dynamic import after the headline and poster have painted, compress models, and keep textures small. A pure shader background written in raw WebGL can be a few kilobytes instead. AnimatedWebs template cards show each live demo's page weight.

Fast animation on phonesPerformance data

How do I respect prefers-reduced-motion in a three.js scene?

Read window.matchMedia('(prefers-reduced-motion: reduce)') before starting the loop, render one still frame instead of animating when it matches, and listen for its change event because visitors can toggle the setting. Stop auto-rotation, camera flights and scroll-driven motion, but keep the scene visible. A canvas that stops without drawing a frame is blank, which is worse than a calm still image.

Reduced motion and performancePerformance answers

Where can I find three.js website templates with live demos?

AnimatedWebs has a 3D and WebGL hub at /templates/3d with technique pages for three.js, particles, shaders, 3D objects, scroll 3D and simulators. Across the catalog of 1,777 items, 376 live demos run WebGL. Each template comes with a live demo where one exists, a full build prompt for your AI coding tool and a design system. There is no source-code download: your AI tool writes the code from the prompt.

3D and WebGL hubThree.js website templates

What is on the AnimatedWebs 3D and WebGL hub?

The hub at /templates/3d groups AnimatedWebs templates by technique: three.js scenes, neural and particle fields, GLSL shaders, 3D objects such as turntables and configurators, scroll-driven 3D stories and interactive simulators. Each technique has its own page, and items can appear under several. You can filter by kind, play live demos, then copy the build prompt into Claude Code, Cursor or another AI tool.

3D and WebGL hubSimulator templatesScroll 3D templates

Are there free three.js website templates?

Yes. AnimatedWebs has a free three.js collection, and 365 of its 1,777 items are free to use on personal and commercial sites with a free account. Free templates include the full build prompt and design system. Pro, at $19 a month or $149 a year, unlocks every template and every live demo's full build prompt. Packs at $29 once unlock 10 Pro templates.

Free three.js templatesFree templatesPricing

Can I add three.js or WebGL to a Lovable site?

Yes. Lovable projects are React apps, so three.js or React Three Fiber can be added as a component that creates the canvas in an effect and cleans it up on unmount. Ask for one fixed canvas behind the content, a pixel ratio cap, a poster fallback and reduced-motion handling in the same prompt. AnimatedWebs has a guide for adding three.js or WebGL to a Lovable site.

Three.js in a Lovable siteAnimatedWebs for Lovable

How do I prompt an AI coding tool to build a three.js hero?

Name the stack, the scene and the limits in one prompt: three.js or React Three Fiber, what moves and how it reacts to cursor or scroll, a pixel ratio cap of 2, a still poster while loading, a WebGL fallback, pausing off-screen and a prefers-reduced-motion still state. Ask for HTML text over the canvas. AnimatedWebs build prompts already spell these details out for each 3D template.

Prompt AI for better animationWebGL hero ideas

Do AnimatedWebs 3D templates include the three.js source code?

No source-code ZIP is included. Each AnimatedWebs template gives you a live demo where one exists, a full build prompt and a design system with DESIGN.md, Tailwind tokens and CSS variables. You paste the prompt into Claude Code, Cursor, Lovable or another AI tool, or fetch it through the MCP server, and the tool writes the three.js or React Three Fiber code in your project.

What's includedMCP server