THREE.JS STAR FIELD
PARTICLE SYSTEMS
By Shane Brumback · · Updated · Free Three.js tutorial · Level 1
To make a star field in Three.js, put thousands of random positions, colors and sizes in one BufferGeometry and draw them with THREE.Points and a PointsMaterial with size attenuation. Move the stars toward the camera each frame and wrap them back, and you are flying through space.
This beginner build adds twinkling stars, a glowing additive nebula, the Planet Quest spaceship with its Space Wow engine plume, mouse and touch steering, and a warp-speed toggle. The scene behind this page is the live demo, and the full copy-paste source is below.
LIVE DEMO
The ship flying behind this page is a live Three.js scene. Launch the full-screen demo to steer with your mouse or finger and hit Space or the Warp button to jump to warp speed. Launch asks for a free Google sign-in first. Press Esc or Exit to return.
Free Google sign-in · Steer: mouse or touch · Warp: Space · Esc to exit
What Is a Particle System?
A particle system draws lots of tiny things, like stars, sparks, snow or dust, as one object. In Three.js that object is THREE.Points: you hand the GPU a single BufferGeometry full of positions and it draws a dot at each one in a single draw call. That is why thousands of stars cost about the same as one mesh.
The trick to the feeling of flight is simple: the ship barely moves. The stars rush toward the camera and jump back to the far end when they pass it, the nebula drifts slower because it is far away, and the camera trails the ship so near stars slide more than far ones. That is parallax.
What You Will Build
- Up to 7,000 colored stars with size attenuation and a per-star twinkle.
- A soft purple, pink and cyan nebula from additive sprite clouds.
- The spaceship from Planet Quest with the flame cone and spark jet from Space Wow.
- Mouse and touch steering with banking, plus a warp-speed streak mode.
- A lighter mobile setup with fewer particles and a capped pixel ratio.
New to Three.js? Start with the spinning cube starter or animating simple 3D objects.
Step-by-Step Code Breakdown
Every excerpt below is copied exactly from the full code further down. Use the Copy button on any window.
1. Set up the renderer, scene and camera
In plain words: we make a dark space world, a camera sitting just behind the ship, and a renderer that draws it, plus two lights so the ship hull shows up. Create a Scene with a near-black background, a PerspectiveCamera, and a WebGLRenderer with ACES tone mapping and a capped pixel ratio on phones, then add a HemisphereLight and a DirectionalLight. The glowTex helper paints a soft round dot used by every star and spark.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x02030a);
const camera = new THREE.PerspectiveCamera(62, innerWidth / innerHeight, 0.1, 1200);
camera.position.set(0, 2.4, 6.5);
let camZ = 6.5; // camera distance behind the ship
const renderer = new THREE.WebGLRenderer({ antialias: !isMobile, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, isMobile ? 1.5 : 2));
renderer.setSize(innerWidth, innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
document.body.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xbfd8ff, 0x1a1030, 1.4));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(3, 5, 4);
scene.add(keyLight);
// a soft round dot drawn on a canvas: the texture for every star and spark
function glowTex(stops) {
const c = document.createElement('canvas');
c.width = c.height = 128;
const g = c.getContext('2d');
const r = g.createRadialGradient(64, 64, 0, 64, 64, 64);
stops.forEach(([o, col]) => r.addColorStop(o, col));
g.fillStyle = r;
g.fillRect(0, 0, 128, 128);
const t = new THREE.CanvasTexture(c);
t.colorSpace = THREE.SRGBColorSpace;
return t;
}
function glowSprite(tex, size, opacity) {
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, transparent: true, opacity, blending: THREE.AdditiveBlending, depthWrite: false }));
sp.scale.setScalar(size);
return sp;
}
const softDot = glowTex([[0, 'rgba(255,255,255,1)'], [0.25, 'rgba(255,255,255,0.6)'], [1, 'rgba(255,255,255,0)']]);
2. Fill a BufferGeometry with star positions, colors and sizes
In plain words: we scatter thousands of dots in a long box in front of the ship and give each one a color, a size and a random twinkle offset. Allocate Float32Arrays for position, color, size and phase, fill them in one loop with random spots, a star palette of blue, white, yellow, orange, cyan and pink, and a few big bright stars, then set them as BufferGeometry attributes.
const STAR_COUNT = isMobile ? 2500 : 7000;
const FIELD = 160; // half width of the star box
const DEPTH = 600; // how far ahead stars spawn
const positions = new Float32Array(STAR_COUNT * 3);
const colors = new Float32Array(STAR_COUNT * 3);
const sizes = new Float32Array(STAR_COUNT);
const phases = new Float32Array(STAR_COUNT);
const palette = [0xffffff, 0xcfe4ff, 0x9cc8ff, 0xfff1c9, 0xffc98a, 0x7ff6ff, 0xff9ee8].map(h => new THREE.Color(h));
const tmp = new THREE.Color();
for (let i = 0; i < STAR_COUNT; i++) {
positions[i * 3] = (Math.random() * 2 - 1) * FIELD;
positions[i * 3 + 1] = (Math.random() * 2 - 1) * FIELD * 0.6;
positions[i * 3 + 2] = -Math.random() * DEPTH;
tmp.copy(palette[Math.floor(Math.random() * palette.length)]).multiplyScalar(0.7 + Math.random() * 0.5);
colors[i * 3] = tmp.r; colors[i * 3 + 1] = tmp.g; colors[i * 3 + 2] = tmp.b;
sizes[i] = Math.random() < 0.04 ? 2.2 + Math.random() * 1.6 : 0.6 + Math.random() * 0.9; // a few big bright stars
phases[i] = Math.random() * Math.PI * 2;
}
const starGeo = new THREE.BufferGeometry();
starGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage));
starGeo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
starGeo.setAttribute('aSize', new THREE.BufferAttribute(sizes, 1));
starGeo.setAttribute('aPhase', new THREE.BufferAttribute(phases, 1));
3. Draw them with PointsMaterial, size attenuation and twinkle
In plain words: one material draws every star as a glowing dot, near stars look bigger, and each one gently pulses. Use PointsMaterial with sizeAttenuation, the soft dot map, vertexColors and AdditiveBlending, then patch gl_PointSize in onBeforeCompile so the aSize and aPhase attributes and a uTime uniform make every star twinkle at its own rate.
const uTime = { value: 0 };
const starMat = new THREE.PointsMaterial({
size: 1.4,
sizeAttenuation: true,
map: softDot,
vertexColors: true,
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending
});
starMat.onBeforeCompile = (shader) => {
shader.uniforms.uTime = uTime;
shader.vertexShader = 'uniform float uTime;\nattribute float aSize;\nattribute float aPhase;\n' +
shader.vertexShader.replace(
'gl_PointSize = size;',
'gl_PointSize = size * aSize * (0.7 + 0.3 * sin(uTime * (1.5 + fract(aPhase) * 3.0) + aPhase * 6.0));'
);
};
const stars = new THREE.Points(starGeo, starMat);
stars.frustumCulled = false;
scene.add(stars);
4. Paint a soft nebula with additive sprite clouds
In plain words: we paint fuzzy blobs on a canvas, tint copies of it purple, pink, cyan and blue, and hang them far away so the colors glow where they overlap. Draw overlapping radial gradients on a 256 pixel canvas, mask the edges with destination-in so no square borders show, and place a group of tinted Sprites with additive blending and random rotation deep in the field.
function cloudTexture() {
const c = document.createElement('canvas');
c.width = c.height = 256;
const g = c.getContext('2d');
for (let i = 0; i < 14; i++) {
const x = 96 + Math.random() * 64, y = 96 + Math.random() * 64, r = 30 + Math.random() * 60;
const grad = g.createRadialGradient(x, y, 0, x, y, r);
grad.addColorStop(0, 'rgba(255,255,255,0.22)');
grad.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = grad;
g.fillRect(0, 0, 256, 256);
}
g.globalCompositeOperation = 'destination-in'; // fade to zero at the edges: no square sprite borders
const mask = g.createRadialGradient(128, 128, 0, 128, 128, 128);
mask.addColorStop(0.4, 'rgba(0,0,0,1)');
mask.addColorStop(1, 'rgba(0,0,0,0)');
g.fillStyle = mask;
g.fillRect(0, 0, 256, 256);
return new THREE.CanvasTexture(c);
}
const nebula = new THREE.Group();
const cloudTex = cloudTexture();
const nebulaColors = [0x7b2cff, 0xff3fa4, 0x2ad1d6, 0x3a5bff, 0xff7a3d];
const NEBULA_COUNT = isMobile ? 9 : 16;
for (let i = 0; i < NEBULA_COUNT; i++) {
const cloud = new THREE.Sprite(new THREE.SpriteMaterial({
map: cloudTex,
color: nebulaColors[i % nebulaColors.length],
transparent: true,
opacity: 0.38,
depthWrite: false,
blending: THREE.AdditiveBlending
}));
cloud.position.set((Math.random() * 2 - 1) * 140, (Math.random() * 2 - 1) * 60, -80 - Math.random() * 520);
cloud.scale.setScalar(120 + Math.random() * 140);
cloud.material.rotation = Math.random() * Math.PI * 2;
nebula.add(cloud);
}
scene.add(nebula);
5. Build the Planet Quest ship
In plain words: we build the same little spaceship used in Planet Quest from a few simple shapes, so there is no model file to download. Combine a cylinder body, a cone nose, a half-sphere cockpit, box wings with glowing cyan tips, a tail fin and an open nozzle using three MeshStandardMaterials, inside a model group that can bank without moving the ship.
const ship = new THREE.Group();
const model = new THREE.Group();
ship.add(model);
{
const hull = new THREE.MeshStandardMaterial({ color: 0xf2f6fb, metalness: 0.15, roughness: 0.4, emissive: 0x4a5a70, emissiveIntensity: 0.55 });
const trim = new THREE.MeshStandardMaterial({ color: 0x2ad1d6, emissive: 0x2ad1d6, emissiveIntensity: 1.3 });
const dark = new THREE.MeshStandardMaterial({ color: 0x5a6a84, metalness: 0.2, roughness: 0.5, emissive: 0x1e2a3c, emissiveIntensity: 0.6 });
const body = new THREE.Mesh(new THREE.CylinderGeometry(0.18, 0.32, 1.6, 12), hull); body.rotation.x = -Math.PI / 2; model.add(body);
const nose = new THREE.Mesh(new THREE.ConeGeometry(0.18, 0.7, 12), hull); nose.rotation.x = -Math.PI / 2; nose.position.z = -1.15; model.add(nose);
const cockpit = new THREE.Mesh(new THREE.SphereGeometry(0.16, 16, 12, 0, Math.PI * 2, 0, Math.PI / 2), new THREE.MeshStandardMaterial({ color: 0x66ccff, emissive: 0x114466, metalness: 0.2, roughness: 0.1 }));
cockpit.position.set(0, 0.16, -0.45); cockpit.scale.set(1, 0.8, 1.8); model.add(cockpit);
const wingGeo = new THREE.BoxGeometry(1.5, 0.05, 0.55);
for (const sx of [-1, 1]) {
const w = new THREE.Mesh(wingGeo, dark); w.position.set(sx * 0.75, -0.04, 0.3); w.rotation.y = sx * 0.25; model.add(w);
const tip = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.06, 0.5), trim); tip.position.set(sx * 1.45, -0.04, 0.45); model.add(tip);
}
const fin = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.45, 0.45), dark); fin.position.set(0, 0.28, 0.6); model.add(fin);
const nozzle = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.26, 0.2, 12, 1, true), dark); nozzle.rotation.x = Math.PI / 2; nozzle.position.z = 0.88; model.add(nozzle);
}
scene.add(ship);
6. Add the Space Wow engine plume
In plain words: we stick a flickering flame cone, two glowing blobs and a stream of yellow-orange sparks onto the back of the ship. A ShaderMaterial cone fades from white-blue to orange and stretches with a uThrust uniform, two additive glow Sprites sit at the nozzle, and a pool of recycled Points sparks shoots backward and fades from yellow to orange in updatePlume.
const PLUME_ADD = { blending: THREE.AdditiveBlending, transparent: true, depthWrite: false };
const plumeConeGeo = new THREE.CylinderGeometry(0.75, 0.12, 1, 20, 6, true);
plumeConeGeo.translate(0, -0.5, 0);
const plumeConeMat = new THREE.ShaderMaterial(Object.assign({
uniforms: { uTime: { value: 0 }, uThrust: { value: 0.6 } },
vertexShader: `uniform float uTime; uniform float uThrust; varying float vT; varying float vF;
void main(){ vec3 p = position; float t = -p.y; vT = t;
float fl = 0.88 + 0.08*sin(uTime*41.0) + 0.05*sin(uTime*23.0);
p.y *= (0.45 + uThrust*1.2) * fl; p.xz *= 1.0 + 0.08*t*sin(uTime*33.0 + t*14.0);
vec4 mv = modelViewMatrix * vec4(p,1.0); vec3 n = normalize(normalMatrix * normal);
vF = abs(dot(n, normalize(-mv.xyz))); gl_Position = projectionMatrix * mv; }`,
fragmentShader: `uniform float uTime; uniform float uThrust; varying float vT; varying float vF;
void main(){ vec3 hot = vec3(0.85,0.93,1.0), mid = vec3(1.0,0.72,0.22), tail = vec3(1.0,0.38,0.06);
vec3 c = mix(hot, mid, smoothstep(0.0,0.3,vT)); c = mix(c, tail, smoothstep(0.3,1.0,vT));
float a = pow(vF,1.4) * pow(1.0-vT,1.3) * (0.25 + 0.75*uThrust) * 1.25;
a *= 0.88 + 0.12*sin(vT*30.0 - uTime*60.0);
gl_FragColor = vec4(c*a, 1.0); }`,
side: THREE.DoubleSide
}, PLUME_ADD));
const plume = new THREE.Group();
plume.position.z = 1.0;
plume.rotation.x = -Math.PI / 2; // the cone's -Y now points out of the ship's tail (+Z)
const plumeOuter = new THREE.Mesh(plumeConeGeo, plumeConeMat); plumeOuter.scale.set(0.16, 2.3, 0.16);
const plumeCore = new THREE.Mesh(plumeConeGeo, plumeConeMat); plumeCore.scale.set(0.13, 2.0, 0.13);
plumeOuter.frustumCulled = plumeCore.frustumCulled = false;
plume.add(plumeOuter, plumeCore);
ship.add(plume);
const plumeHot = glowSprite(glowTex([[0, 'rgba(255,255,255,1)'], [0.3, 'rgba(170,215,255,0.85)'], [1, 'rgba(60,120,255,0)']]), 0.75, 1);
plumeHot.position.z = 1.05; ship.add(plumeHot);
const plumeWarm = glowSprite(glowTex([[0, 'rgba(255,230,140,0.9)'], [0.4, 'rgba(255,150,40,0.45)'], [1, 'rgba(255,80,0,0)']]), 0.9, 0.7);
plumeWarm.position.z = 1.3; ship.add(plumeWarm);
// yellow-to-orange jet sparks, recycled from a fixed pool
const JN = isMobile ? 400 : 1100;
const jPos = new Float32Array(JN * 3), jVel = new Float32Array(JN * 3), jLife = new Float32Array(JN), jCol = new Float32Array(JN * 3);
for (let i = 0; i < JN; i++) jPos[i * 3 + 1] = 1e5;
const jGeo = new THREE.BufferGeometry();
jGeo.setAttribute('position', new THREE.BufferAttribute(jPos, 3).setUsage(THREE.DynamicDrawUsage));
jGeo.setAttribute('color', new THREE.BufferAttribute(jCol, 3).setUsage(THREE.DynamicDrawUsage));
const jet = new THREE.Points(jGeo, new THREE.PointsMaterial(Object.assign({ size: 0.2, map: softDot, vertexColors: true }, PLUME_ADD)));
jet.frustumCulled = false;
ship.add(jet);
let jIdx = 0;
function updatePlume(dt, thrust) {
const th = THREE.MathUtils.clamp(thrust, 0, 1.2);
plumeConeMat.uniforms.uTime.value += dt;
plumeConeMat.uniforms.uThrust.value = th;
plumeHot.scale.setScalar(0.22 + 0.12 * th + Math.random() * 0.03);
plumeWarm.scale.setScalar((0.22 + 0.28 * th) * (0.95 + Math.random() * 0.1));
plumeWarm.material.opacity = 0.15 + 0.3 * th;
const n = Math.floor((250 + 900 * th) * dt * (isMobile ? 0.4 : 1) + Math.random());
for (let k = 0; k < n; k++) {
const i3 = jIdx * 3, sp = 10 + 12 * th + Math.random() * 3;
jPos[i3] = (Math.random() - 0.5) * 0.14; jPos[i3 + 1] = (Math.random() - 0.5) * 0.14; jPos[i3 + 2] = 1.0;
jVel[i3] = (Math.random() - 0.5) * 0.25; jVel[i3 + 1] = (Math.random() - 0.5) * 0.25; jVel[i3 + 2] = sp;
jLife[jIdx] = 1;
jIdx = (jIdx + 1) % JN;
}
const drag = Math.exp(-2.2 * dt);
for (let i = 0; i < JN; i++) {
const i3 = i * 3;
if (jLife[i] <= 0) { jPos[i3 + 1] = 1e5; continue; }
jLife[i] -= dt * 2.4;
jVel[i3] *= drag; jVel[i3 + 1] *= drag; jVel[i3 + 2] *= drag;
jPos[i3] += jVel[i3] * dt; jPos[i3 + 1] += jVel[i3 + 1] * dt; jPos[i3 + 2] += jVel[i3 + 2] * dt;
const L = Math.max(jLife[i], 0), a = L * L * 0.4;
jCol[i3] = a; jCol[i3 + 1] = (0.35 + 0.5 * L) * a; jCol[i3 + 2] = 0.12 * L * a;
}
jGeo.attributes.position.needsUpdate = true;
jGeo.attributes.color.needsUpdate = true;
}
7. Make warp-speed streaks and a toggle
In plain words: when you press Space or the Warp button, hundreds of colored lines appear and stretch longer as the ship speeds up. Build a LineSegments geometry with a bright head and black tail per line, keep its opacity at zero, and flip a warpTarget value with toggleWarp from the Space key or a button.
const STREAKS = isMobile ? 260 : 1000;
const sPos = new Float32Array(STREAKS * 6);
const sCol = new Float32Array(STREAKS * 6);
for (let i = 0; i < STREAKS; i++) {
const a = Math.random() * Math.PI * 2, r = 4 + Math.random() * 60;
const x = Math.cos(a) * r, y = Math.sin(a) * r * 0.7, z = -Math.random() * 300;
sPos.set([x, y, z, x, y, z], i * 6);
const c = palette[i % palette.length];
sCol.set([c.r * 1.8, c.g * 1.8, c.b * 1.8, c.r * 0.15, c.g * 0.15, c.b * 0.15], i * 6); // extra-bright head, fading tail
}
const streakGeo = new THREE.BufferGeometry();
streakGeo.setAttribute('position', new THREE.BufferAttribute(sPos, 3).setUsage(THREE.DynamicDrawUsage));
streakGeo.setAttribute('color', new THREE.BufferAttribute(sCol, 3));
const streakMat = new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false });
const streaks = new THREE.LineSegments(streakGeo, streakMat);
streaks.frustumCulled = false;
scene.add(streaks);
let warpTarget = 0, warp = 0;
function toggleWarp(on) {
warpTarget = typeof on === 'boolean' ? (on ? 1 : 0) : (warpTarget ? 0 : 1);
return warpTarget === 1;
}
addEventListener('keydown', (e) => {
if (e.code === 'Space' && steerEnabled) { e.preventDefault(); toggleWarp(); }
});
8. Steer with the mouse or touch
In plain words: the ship chases your mouse or finger around the screen. Store the pointer position from pointermove as -1 to 1 values; touch only steers inside the full-screen demo so phones can still scroll the page.
let steerEnabled = false;
const pointer = new THREE.Vector2();
addEventListener('pointermove', (e) => {
if (e.pointerType !== 'mouse' && !steerEnabled) return; // on phones only steer inside the demo
pointer.set((e.clientX / innerWidth) * 2 - 1, (e.clientY / innerHeight) * 2 - 1);
});
const shipVel = new THREE.Vector2();
9. Run the animation loop: fly, twinkle and wrap
In plain words: every frame the stars rush toward you and jump back to the far end, the ship follows the pointer and banks, and the camera trails it for parallax. Damp warp toward its target, move every star by speed times delta and wrap it, drift the nebula at a slower rate, stretch the streaks, ease the ship toward the pointer and roll it by its sideways speed, update the plume, widen the FOV during warp and render.
const clock = new THREE.Clock();
const CRUISE = 22, WARP = 190;
function animate() {
requestAnimationFrame(animate);
const dt = Math.max(Math.min(clock.getDelta(), 0.05), 0.001);
const t = (uTime.value += dt);
warp = THREE.MathUtils.damp(warp, warpTarget, 2.2, dt);
const speed = CRUISE + (WARP - CRUISE) * warp;
// stars rush toward the camera and wrap back to the far end
const p = starGeo.attributes.position.array;
for (let i = 0; i < STAR_COUNT; i++) {
const k = i * 3 + 2;
p[k] += speed * dt;
if (p[k] > camera.position.z + 2) {
p[k] -= DEPTH;
p[k - 2] = (Math.random() * 2 - 1) * FIELD;
p[k - 1] = (Math.random() * 2 - 1) * FIELD * 0.6;
}
}
starGeo.attributes.position.needsUpdate = true;
// nebula drifts slower (it is far away) and slowly turns
for (const cloud of nebula.children) {
cloud.position.z += speed * dt * 0.35;
cloud.material.rotation += dt * 0.02;
if (cloud.position.z > camera.position.z + 40) cloud.position.z -= 620;
}
// warp streaks: length and brightness follow the warp amount
streakMat.opacity = warp;
streaks.visible = warp > 0.02;
if (streaks.visible) {
const len = 2 + warp * 40;
for (let i = 0; i < STREAKS; i++) {
const o = i * 6;
sPos[o + 2] += speed * dt;
if (sPos[o + 2] > camera.position.z) sPos[o + 2] -= 300;
sPos[o + 5] = sPos[o + 2] - len;
}
streakGeo.attributes.position.needsUpdate = true;
}
// ship follows the pointer (or a gentle auto drift), banks into turns
const auto = steerEnabled ? 0 : 1;
const tx = (pointer.x * (1 - auto * 0.6) + Math.sin(t * 0.4) * 0.5 * auto) * 3.2;
const ty = (-pointer.y * (1 - auto * 0.6) + Math.sin(t * 0.63) * 0.35 * auto) * 1.8;
const nx = THREE.MathUtils.damp(ship.position.x, tx, 2.5, dt);
const ny = THREE.MathUtils.damp(ship.position.y, ty, 2.5, dt);
shipVel.set((nx - ship.position.x) / dt, (ny - ship.position.y) / dt);
ship.position.set(nx, ny, 0);
model.rotation.z = THREE.MathUtils.damp(model.rotation.z, -shipVel.x * 0.18, 6, dt);
model.rotation.x = THREE.MathUtils.damp(model.rotation.x, shipVel.y * 0.08, 6, dt);
model.position.y = Math.sin(t * 2.1) * 0.04;
updatePlume(dt, 0.6 + warp * 0.6);
// gentle parallax: the camera trails the ship, so near stars slide more than far ones
camera.position.x = THREE.MathUtils.damp(camera.position.x, ship.position.x * 0.55, 2, dt);
camera.position.y = THREE.MathUtils.damp(camera.position.y, 2.4 + ship.position.y * 0.45, 2, dt);
camera.position.z = THREE.MathUtils.damp(camera.position.z, camZ, 2, dt);
camera.fov = 62 + warp * 18 + (Math.random() - 0.5) * warp * 0.6;
camera.updateProjectionMatrix();
camera.lookAt(ship.position.x * 0.8, ship.position.y * 0.8 + 0.4, -10);
renderer.render(scene, camera);
}
animate();
10. Handle resizing
In plain words: when the window changes size, the picture is redrawn at the new shape without stretching. On resize, update the camera aspect and projection matrix and call renderer.setSize.
function onResize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
}
addEventListener('resize', onResize);
Want more particles? Try the audio-driven particle systems tutorial, or add a post-processing glow with bloom.
The Full Code
Paste this module into a <script type="module"> in an HTML page whose import map points three at https://unpkg.com/three@0.160.0/build/three.module.js. No build tools or model files needed. Or click Run to open exactly this code as a standalone page.
// Three.js Star Field Particle Systems - Level 1 tutorial scene (shanebrumback.com)
// Colored twinkling stars, additive nebula clouds, the Planet Quest ship with its
// Space Wow engine plume, mouse / touch steering and a warp-speed streak toggle.
import * as THREE from 'three';
const isMobile = matchMedia('(max-width: 768px)').matches || matchMedia('(pointer: coarse)').matches;
// ---------- 1. Renderer, scene and camera ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x02030a);
const camera = new THREE.PerspectiveCamera(62, innerWidth / innerHeight, 0.1, 1200);
camera.position.set(0, 2.4, 6.5);
let camZ = 6.5; // camera distance behind the ship
const renderer = new THREE.WebGLRenderer({ antialias: !isMobile, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, isMobile ? 1.5 : 2));
renderer.setSize(innerWidth, innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
document.body.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xbfd8ff, 0x1a1030, 1.4));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(3, 5, 4);
scene.add(keyLight);
// a soft round dot drawn on a canvas: the texture for every star and spark
function glowTex(stops) {
const c = document.createElement('canvas');
c.width = c.height = 128;
const g = c.getContext('2d');
const r = g.createRadialGradient(64, 64, 0, 64, 64, 64);
stops.forEach(([o, col]) => r.addColorStop(o, col));
g.fillStyle = r;
g.fillRect(0, 0, 128, 128);
const t = new THREE.CanvasTexture(c);
t.colorSpace = THREE.SRGBColorSpace;
return t;
}
function glowSprite(tex, size, opacity) {
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, transparent: true, opacity, blending: THREE.AdditiveBlending, depthWrite: false }));
sp.scale.setScalar(size);
return sp;
}
const softDot = glowTex([[0, 'rgba(255,255,255,1)'], [0.25, 'rgba(255,255,255,0.6)'], [1, 'rgba(255,255,255,0)']]);
// ---------- 2. Star positions, colors and sizes in a BufferGeometry ----------
const STAR_COUNT = isMobile ? 2500 : 7000;
const FIELD = 160; // half width of the star box
const DEPTH = 600; // how far ahead stars spawn
const positions = new Float32Array(STAR_COUNT * 3);
const colors = new Float32Array(STAR_COUNT * 3);
const sizes = new Float32Array(STAR_COUNT);
const phases = new Float32Array(STAR_COUNT);
const palette = [0xffffff, 0xcfe4ff, 0x9cc8ff, 0xfff1c9, 0xffc98a, 0x7ff6ff, 0xff9ee8].map(h => new THREE.Color(h));
const tmp = new THREE.Color();
for (let i = 0; i < STAR_COUNT; i++) {
positions[i * 3] = (Math.random() * 2 - 1) * FIELD;
positions[i * 3 + 1] = (Math.random() * 2 - 1) * FIELD * 0.6;
positions[i * 3 + 2] = -Math.random() * DEPTH;
tmp.copy(palette[Math.floor(Math.random() * palette.length)]).multiplyScalar(0.7 + Math.random() * 0.5);
colors[i * 3] = tmp.r; colors[i * 3 + 1] = tmp.g; colors[i * 3 + 2] = tmp.b;
sizes[i] = Math.random() < 0.04 ? 2.2 + Math.random() * 1.6 : 0.6 + Math.random() * 0.9; // a few big bright stars
phases[i] = Math.random() * Math.PI * 2;
}
const starGeo = new THREE.BufferGeometry();
starGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage));
starGeo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
starGeo.setAttribute('aSize', new THREE.BufferAttribute(sizes, 1));
starGeo.setAttribute('aPhase', new THREE.BufferAttribute(phases, 1));
// ---------- 3. PointsMaterial with size attenuation and a twinkle ----------
const uTime = { value: 0 };
const starMat = new THREE.PointsMaterial({
size: 1.4,
sizeAttenuation: true,
map: softDot,
vertexColors: true,
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending
});
starMat.onBeforeCompile = (shader) => {
shader.uniforms.uTime = uTime;
shader.vertexShader = 'uniform float uTime;\nattribute float aSize;\nattribute float aPhase;\n' +
shader.vertexShader.replace(
'gl_PointSize = size;',
'gl_PointSize = size * aSize * (0.7 + 0.3 * sin(uTime * (1.5 + fract(aPhase) * 3.0) + aPhase * 6.0));'
);
};
const stars = new THREE.Points(starGeo, starMat);
stars.frustumCulled = false;
scene.add(stars);
// ---------- 4. A soft nebula of additive sprite clouds ----------
function cloudTexture() {
const c = document.createElement('canvas');
c.width = c.height = 256;
const g = c.getContext('2d');
for (let i = 0; i < 14; i++) {
const x = 96 + Math.random() * 64, y = 96 + Math.random() * 64, r = 30 + Math.random() * 60;
const grad = g.createRadialGradient(x, y, 0, x, y, r);
grad.addColorStop(0, 'rgba(255,255,255,0.22)');
grad.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = grad;
g.fillRect(0, 0, 256, 256);
}
g.globalCompositeOperation = 'destination-in'; // fade to zero at the edges: no square sprite borders
const mask = g.createRadialGradient(128, 128, 0, 128, 128, 128);
mask.addColorStop(0.4, 'rgba(0,0,0,1)');
mask.addColorStop(1, 'rgba(0,0,0,0)');
g.fillStyle = mask;
g.fillRect(0, 0, 256, 256);
return new THREE.CanvasTexture(c);
}
const nebula = new THREE.Group();
const cloudTex = cloudTexture();
const nebulaColors = [0x7b2cff, 0xff3fa4, 0x2ad1d6, 0x3a5bff, 0xff7a3d];
const NEBULA_COUNT = isMobile ? 9 : 16;
for (let i = 0; i < NEBULA_COUNT; i++) {
const cloud = new THREE.Sprite(new THREE.SpriteMaterial({
map: cloudTex,
color: nebulaColors[i % nebulaColors.length],
transparent: true,
opacity: 0.38,
depthWrite: false,
blending: THREE.AdditiveBlending
}));
cloud.position.set((Math.random() * 2 - 1) * 140, (Math.random() * 2 - 1) * 60, -80 - Math.random() * 520);
cloud.scale.setScalar(120 + Math.random() * 140);
cloud.material.rotation = Math.random() * Math.PI * 2;
nebula.add(cloud);
}
scene.add(nebula);
// ---------- 5. The Planet Quest ship (built from simple shapes, no model file) ----------
const ship = new THREE.Group();
const model = new THREE.Group();
ship.add(model);
{
const hull = new THREE.MeshStandardMaterial({ color: 0xf2f6fb, metalness: 0.15, roughness: 0.4, emissive: 0x4a5a70, emissiveIntensity: 0.55 });
const trim = new THREE.MeshStandardMaterial({ color: 0x2ad1d6, emissive: 0x2ad1d6, emissiveIntensity: 1.3 });
const dark = new THREE.MeshStandardMaterial({ color: 0x5a6a84, metalness: 0.2, roughness: 0.5, emissive: 0x1e2a3c, emissiveIntensity: 0.6 });
const body = new THREE.Mesh(new THREE.CylinderGeometry(0.18, 0.32, 1.6, 12), hull); body.rotation.x = -Math.PI / 2; model.add(body);
const nose = new THREE.Mesh(new THREE.ConeGeometry(0.18, 0.7, 12), hull); nose.rotation.x = -Math.PI / 2; nose.position.z = -1.15; model.add(nose);
const cockpit = new THREE.Mesh(new THREE.SphereGeometry(0.16, 16, 12, 0, Math.PI * 2, 0, Math.PI / 2), new THREE.MeshStandardMaterial({ color: 0x66ccff, emissive: 0x114466, metalness: 0.2, roughness: 0.1 }));
cockpit.position.set(0, 0.16, -0.45); cockpit.scale.set(1, 0.8, 1.8); model.add(cockpit);
const wingGeo = new THREE.BoxGeometry(1.5, 0.05, 0.55);
for (const sx of [-1, 1]) {
const w = new THREE.Mesh(wingGeo, dark); w.position.set(sx * 0.75, -0.04, 0.3); w.rotation.y = sx * 0.25; model.add(w);
const tip = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.06, 0.5), trim); tip.position.set(sx * 1.45, -0.04, 0.45); model.add(tip);
}
const fin = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.45, 0.45), dark); fin.position.set(0, 0.28, 0.6); model.add(fin);
const nozzle = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.26, 0.2, 12, 1, true), dark); nozzle.rotation.x = Math.PI / 2; nozzle.position.z = 0.88; model.add(nozzle);
}
scene.add(ship);
// ---------- 6. Space Wow style engine plume ----------
const PLUME_ADD = { blending: THREE.AdditiveBlending, transparent: true, depthWrite: false };
const plumeConeGeo = new THREE.CylinderGeometry(0.75, 0.12, 1, 20, 6, true);
plumeConeGeo.translate(0, -0.5, 0);
const plumeConeMat = new THREE.ShaderMaterial(Object.assign({
uniforms: { uTime: { value: 0 }, uThrust: { value: 0.6 } },
vertexShader: `uniform float uTime; uniform float uThrust; varying float vT; varying float vF;
void main(){ vec3 p = position; float t = -p.y; vT = t;
float fl = 0.88 + 0.08*sin(uTime*41.0) + 0.05*sin(uTime*23.0);
p.y *= (0.45 + uThrust*1.2) * fl; p.xz *= 1.0 + 0.08*t*sin(uTime*33.0 + t*14.0);
vec4 mv = modelViewMatrix * vec4(p,1.0); vec3 n = normalize(normalMatrix * normal);
vF = abs(dot(n, normalize(-mv.xyz))); gl_Position = projectionMatrix * mv; }`,
fragmentShader: `uniform float uTime; uniform float uThrust; varying float vT; varying float vF;
void main(){ vec3 hot = vec3(0.85,0.93,1.0), mid = vec3(1.0,0.72,0.22), tail = vec3(1.0,0.38,0.06);
vec3 c = mix(hot, mid, smoothstep(0.0,0.3,vT)); c = mix(c, tail, smoothstep(0.3,1.0,vT));
float a = pow(vF,1.4) * pow(1.0-vT,1.3) * (0.25 + 0.75*uThrust) * 1.25;
a *= 0.88 + 0.12*sin(vT*30.0 - uTime*60.0);
gl_FragColor = vec4(c*a, 1.0); }`,
side: THREE.DoubleSide
}, PLUME_ADD));
const plume = new THREE.Group();
plume.position.z = 1.0;
plume.rotation.x = -Math.PI / 2; // the cone's -Y now points out of the ship's tail (+Z)
const plumeOuter = new THREE.Mesh(plumeConeGeo, plumeConeMat); plumeOuter.scale.set(0.16, 2.3, 0.16);
const plumeCore = new THREE.Mesh(plumeConeGeo, plumeConeMat); plumeCore.scale.set(0.13, 2.0, 0.13);
plumeOuter.frustumCulled = plumeCore.frustumCulled = false;
plume.add(plumeOuter, plumeCore);
ship.add(plume);
const plumeHot = glowSprite(glowTex([[0, 'rgba(255,255,255,1)'], [0.3, 'rgba(170,215,255,0.85)'], [1, 'rgba(60,120,255,0)']]), 0.75, 1);
plumeHot.position.z = 1.05; ship.add(plumeHot);
const plumeWarm = glowSprite(glowTex([[0, 'rgba(255,230,140,0.9)'], [0.4, 'rgba(255,150,40,0.45)'], [1, 'rgba(255,80,0,0)']]), 0.9, 0.7);
plumeWarm.position.z = 1.3; ship.add(plumeWarm);
// yellow-to-orange jet sparks, recycled from a fixed pool
const JN = isMobile ? 400 : 1100;
const jPos = new Float32Array(JN * 3), jVel = new Float32Array(JN * 3), jLife = new Float32Array(JN), jCol = new Float32Array(JN * 3);
for (let i = 0; i < JN; i++) jPos[i * 3 + 1] = 1e5;
const jGeo = new THREE.BufferGeometry();
jGeo.setAttribute('position', new THREE.BufferAttribute(jPos, 3).setUsage(THREE.DynamicDrawUsage));
jGeo.setAttribute('color', new THREE.BufferAttribute(jCol, 3).setUsage(THREE.DynamicDrawUsage));
const jet = new THREE.Points(jGeo, new THREE.PointsMaterial(Object.assign({ size: 0.2, map: softDot, vertexColors: true }, PLUME_ADD)));
jet.frustumCulled = false;
ship.add(jet);
let jIdx = 0;
function updatePlume(dt, thrust) {
const th = THREE.MathUtils.clamp(thrust, 0, 1.2);
plumeConeMat.uniforms.uTime.value += dt;
plumeConeMat.uniforms.uThrust.value = th;
plumeHot.scale.setScalar(0.22 + 0.12 * th + Math.random() * 0.03);
plumeWarm.scale.setScalar((0.22 + 0.28 * th) * (0.95 + Math.random() * 0.1));
plumeWarm.material.opacity = 0.15 + 0.3 * th;
const n = Math.floor((250 + 900 * th) * dt * (isMobile ? 0.4 : 1) + Math.random());
for (let k = 0; k < n; k++) {
const i3 = jIdx * 3, sp = 10 + 12 * th + Math.random() * 3;
jPos[i3] = (Math.random() - 0.5) * 0.14; jPos[i3 + 1] = (Math.random() - 0.5) * 0.14; jPos[i3 + 2] = 1.0;
jVel[i3] = (Math.random() - 0.5) * 0.25; jVel[i3 + 1] = (Math.random() - 0.5) * 0.25; jVel[i3 + 2] = sp;
jLife[jIdx] = 1;
jIdx = (jIdx + 1) % JN;
}
const drag = Math.exp(-2.2 * dt);
for (let i = 0; i < JN; i++) {
const i3 = i * 3;
if (jLife[i] <= 0) { jPos[i3 + 1] = 1e5; continue; }
jLife[i] -= dt * 2.4;
jVel[i3] *= drag; jVel[i3 + 1] *= drag; jVel[i3 + 2] *= drag;
jPos[i3] += jVel[i3] * dt; jPos[i3 + 1] += jVel[i3 + 1] * dt; jPos[i3 + 2] += jVel[i3 + 2] * dt;
const L = Math.max(jLife[i], 0), a = L * L * 0.4;
jCol[i3] = a; jCol[i3 + 1] = (0.35 + 0.5 * L) * a; jCol[i3 + 2] = 0.12 * L * a;
}
jGeo.attributes.position.needsUpdate = true;
jGeo.attributes.color.needsUpdate = true;
}
// ---------- 7. Warp-speed streaks ----------
const STREAKS = isMobile ? 260 : 1000;
const sPos = new Float32Array(STREAKS * 6);
const sCol = new Float32Array(STREAKS * 6);
for (let i = 0; i < STREAKS; i++) {
const a = Math.random() * Math.PI * 2, r = 4 + Math.random() * 60;
const x = Math.cos(a) * r, y = Math.sin(a) * r * 0.7, z = -Math.random() * 300;
sPos.set([x, y, z, x, y, z], i * 6);
const c = palette[i % palette.length];
sCol.set([c.r * 1.8, c.g * 1.8, c.b * 1.8, c.r * 0.15, c.g * 0.15, c.b * 0.15], i * 6); // extra-bright head, fading tail
}
const streakGeo = new THREE.BufferGeometry();
streakGeo.setAttribute('position', new THREE.BufferAttribute(sPos, 3).setUsage(THREE.DynamicDrawUsage));
streakGeo.setAttribute('color', new THREE.BufferAttribute(sCol, 3));
const streakMat = new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false });
const streaks = new THREE.LineSegments(streakGeo, streakMat);
streaks.frustumCulled = false;
scene.add(streaks);
let warpTarget = 0, warp = 0;
function toggleWarp(on) {
warpTarget = typeof on === 'boolean' ? (on ? 1 : 0) : (warpTarget ? 0 : 1);
return warpTarget === 1;
}
addEventListener('keydown', (e) => {
if (e.code === 'Space' && steerEnabled) { e.preventDefault(); toggleWarp(); }
});
// ---------- 8. Mouse and touch steering ----------
let steerEnabled = false;
const pointer = new THREE.Vector2();
addEventListener('pointermove', (e) => {
if (e.pointerType !== 'mouse' && !steerEnabled) return; // on phones only steer inside the demo
pointer.set((e.clientX / innerWidth) * 2 - 1, (e.clientY / innerHeight) * 2 - 1);
});
const shipVel = new THREE.Vector2();
// ---------- 9. The animation loop: fly, twinkle and wrap ----------
const clock = new THREE.Clock();
const CRUISE = 22, WARP = 190;
function animate() {
requestAnimationFrame(animate);
const dt = Math.max(Math.min(clock.getDelta(), 0.05), 0.001);
const t = (uTime.value += dt);
warp = THREE.MathUtils.damp(warp, warpTarget, 2.2, dt);
const speed = CRUISE + (WARP - CRUISE) * warp;
// stars rush toward the camera and wrap back to the far end
const p = starGeo.attributes.position.array;
for (let i = 0; i < STAR_COUNT; i++) {
const k = i * 3 + 2;
p[k] += speed * dt;
if (p[k] > camera.position.z + 2) {
p[k] -= DEPTH;
p[k - 2] = (Math.random() * 2 - 1) * FIELD;
p[k - 1] = (Math.random() * 2 - 1) * FIELD * 0.6;
}
}
starGeo.attributes.position.needsUpdate = true;
// nebula drifts slower (it is far away) and slowly turns
for (const cloud of nebula.children) {
cloud.position.z += speed * dt * 0.35;
cloud.material.rotation += dt * 0.02;
if (cloud.position.z > camera.position.z + 40) cloud.position.z -= 620;
}
// warp streaks: length and brightness follow the warp amount
streakMat.opacity = warp;
streaks.visible = warp > 0.02;
if (streaks.visible) {
const len = 2 + warp * 40;
for (let i = 0; i < STREAKS; i++) {
const o = i * 6;
sPos[o + 2] += speed * dt;
if (sPos[o + 2] > camera.position.z) sPos[o + 2] -= 300;
sPos[o + 5] = sPos[o + 2] - len;
}
streakGeo.attributes.position.needsUpdate = true;
}
// ship follows the pointer (or a gentle auto drift), banks into turns
const auto = steerEnabled ? 0 : 1;
const tx = (pointer.x * (1 - auto * 0.6) + Math.sin(t * 0.4) * 0.5 * auto) * 3.2;
const ty = (-pointer.y * (1 - auto * 0.6) + Math.sin(t * 0.63) * 0.35 * auto) * 1.8;
const nx = THREE.MathUtils.damp(ship.position.x, tx, 2.5, dt);
const ny = THREE.MathUtils.damp(ship.position.y, ty, 2.5, dt);
shipVel.set((nx - ship.position.x) / dt, (ny - ship.position.y) / dt);
ship.position.set(nx, ny, 0);
model.rotation.z = THREE.MathUtils.damp(model.rotation.z, -shipVel.x * 0.18, 6, dt);
model.rotation.x = THREE.MathUtils.damp(model.rotation.x, shipVel.y * 0.08, 6, dt);
model.position.y = Math.sin(t * 2.1) * 0.04;
updatePlume(dt, 0.6 + warp * 0.6);
// gentle parallax: the camera trails the ship, so near stars slide more than far ones
camera.position.x = THREE.MathUtils.damp(camera.position.x, ship.position.x * 0.55, 2, dt);
camera.position.y = THREE.MathUtils.damp(camera.position.y, 2.4 + ship.position.y * 0.45, 2, dt);
camera.position.z = THREE.MathUtils.damp(camera.position.z, camZ, 2, dt);
camera.fov = 62 + warp * 18 + (Math.random() - 0.5) * warp * 0.6;
camera.updateProjectionMatrix();
camera.lookAt(ship.position.x * 0.8, ship.position.y * 0.8 + 0.4, -10);
renderer.render(scene, camera);
}
animate();
// ---------- 10. Resize ----------
function onResize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
}
addEventListener('resize', onResize);
Frequently Asked Questions
How do you make a star field in Three.js?
Fill a BufferGeometry with thousands of random positions in a Float32Array, give it color and size attributes, and draw it with THREE.Points and a PointsMaterial using a soft round texture and additive blending. Move the stars toward the camera every frame and wrap them to the far end for endless flight.
What does sizeAttenuation do on PointsMaterial?
With sizeAttenuation set to true, each point gets smaller the farther it is from the camera, so near stars look big and far stars look tiny. That depth cue makes a flat cloud of dots feel like real 3D space.
How do you make stars twinkle?
Give each star a random phase attribute and multiply its gl_PointSize by a sine wave of time plus that phase. In this demo the change is patched into PointsMaterial with onBeforeCompile, so every star pulses at its own rate on the GPU.
How is the nebula made?
The nebula is a group of large Sprites that share one canvas texture of soft overlapping gradients. Each sprite is tinted purple, pink, cyan, blue or orange and drawn with AdditiveBlending, so overlapping clouds glow brighter.
How does the warp-speed effect work?
Pressing Space or the Warp button raises a warp value from 0 to 1. It speeds up the stars, fades in LineSegments streaks that stretch with speed, boosts the engine plume and widens the camera field of view.
Will this star field run on phones?
Yes. On phones the demo uses fewer stars, nebula clouds, streaks and plume sparks, turns off antialiasing and caps the pixel ratio at 1.5 so it stays smooth.
Why do I need to sign in to launch the live demo?
The tutorial and its full code are free to read. The full-screen Live Demo asks for a free Google sign-in first, the same gate used across the site, so I know who is learning from these tutorials.
Play It and Keep Learning
This ship flies the whole solar system in Planet Quest. Browse every Three.js tutorial, read the articles, or search the site.
Need Three.js particles or WebGL work? I take freelance and contract work: contact me.