stars starfield twinkle parallax dark space night
Starfield
starfield.js
/**
* Starfield — Twinkling stars with optional pointer parallax.
* Category: backgrounds | Animate: true | Interactive: true | Complexity: low
*/
export default function starfield(ctx, state) {
const COUNT = 120;
const COLOR = '255, 255, 255';
let stars = [];
function spawn(width, height) {
return Array.from({ length: COUNT }, () => ({
x: Math.random() * width,
y: Math.random() * height,
r: 0.3 + Math.random() * 1.8,
twinkleSpeed: 0.5 + Math.random() * 2,
twinkleOffset: Math.random() * Math.PI * 2,
parallax: 0.005 + Math.random() * 0.02,
}));
}
stars = spawn(state.width, state.height);
return {
resize({ width, height }) {
stars = spawn(width, height);
},
frame({ width, height, time, pointer, reducedMotion }) {
const px = pointer.inside ? pointer.x / width - 0.5 : 0;
const py = pointer.inside ? pointer.y / height - 0.5 : 0;
for (const s of stars) {
const t = reducedMotion ? s.twinkleOffset : time * s.twinkleSpeed + s.twinkleOffset;
const alpha = 0.3 + 0.7 * (0.5 + 0.5 * Math.sin(t));
const ox = reducedMotion ? 0 : px * s.parallax * width * 8;
const oy = reducedMotion ? 0 : py * s.parallax * height * 8;
ctx.beginPath();
ctx.arc(s.x + ox, s.y + oy, s.r, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${COLOR}, ${alpha})`;
ctx.fill();
}
},
destroy() {
stars = [];
},
};
}
embed.html
<canvas id="canvas-effect" style="width:100%;height:400px;display:block" aria-hidden="true"></canvas>
<script>
/**
* mountCanvas — Minimal runtime for Canvas effects.
*
* Handles HiDPI scaling, ResizeObserver, RAF loop, pointer tracking,
* reduced-motion, and cleanup. The effect only implements draw logic.
*
* @param {HTMLCanvasElement} canvas
* @param {(ctx: CanvasRenderingContext2D, state: object) => object} createEffect
* @param {object} [options]
* @returns {() => void} destroy function
*/
function mountCanvas(canvas, createEffect, options = {}) {
const ctx = canvas.getContext('2d', { alpha: true });
if (!ctx) throw new Error('2D context not available');
const opts = {
animate: true,
clear: true,
maxDpr: 2,
pauseWhenHidden: true,
respectReducedMotion: true,
...options,
};
const reducedMotion =
opts.respectReducedMotion && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const state = {
canvas,
ctx,
width: 0,
height: 0,
pixelWidth: 0,
pixelHeight: 0,
dpr: 1,
time: 0,
delta: 0,
frame: 0,
playing: false,
reducedMotion,
pointer: { x: 0, y: 0, inside: false, down: false },
};
let rafId = 0;
let lastTime = 0;
let disposed = false;
function measure() {
const rect = canvas.getBoundingClientRect();
const w = Math.max(1, rect.width);
const h = Math.max(1, rect.height);
const dpr = Math.min(window.devicePixelRatio || 1, opts.maxDpr);
const pw = Math.round(w * dpr);
const ph = Math.round(h * dpr);
if (canvas.width !== pw || canvas.height !== ph) {
canvas.width = pw;
canvas.height = ph;
}
state.width = w;
state.height = h;
state.pixelWidth = pw;
state.pixelHeight = ph;
state.dpr = dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function clear() {
ctx.clearRect(0, 0, state.width, state.height);
}
const effect = createEffect(ctx, state) || {};
function onResize() {
measure();
effect.resize?.(state);
if (!opts.animate || reducedMotion) {
if (opts.clear) clear();
effect.frame?.(state);
}
}
function loop(now) {
if (disposed) return;
if (opts.pauseWhenHidden && document.hidden) {
rafId = requestAnimationFrame(loop);
return;
}
state.delta = lastTime ? (now - lastTime) / 1000 : 0;
state.time = now / 1000;
state.frame += 1;
lastTime = now;
if (opts.clear) clear();
effect.frame?.(state);
rafId = requestAnimationFrame(loop);
}
function onPointerMove(e) {
const rect = canvas.getBoundingClientRect();
state.pointer.x = e.clientX - rect.left;
state.pointer.y = e.clientY - rect.top;
if (!opts.animate || reducedMotion) {
if (opts.clear) clear();
effect.frame?.(state);
}
}
function onPointerEnter() {
state.pointer.inside = true;
}
function onPointerLeave() {
state.pointer.inside = false;
state.pointer.down = false;
}
function onPointerDown() {
state.pointer.down = true;
}
function onPointerUp() {
state.pointer.down = false;
}
const ro = new ResizeObserver(onResize);
ro.observe(canvas);
canvas.addEventListener('pointermove', onPointerMove);
canvas.addEventListener('pointerenter', onPointerEnter);
canvas.addEventListener('pointerleave', onPointerLeave);
canvas.addEventListener('pointerdown', onPointerDown);
window.addEventListener('pointerup', onPointerUp);
measure();
if (opts.animate && !reducedMotion) {
state.playing = true;
rafId = requestAnimationFrame(loop);
} else {
effect.frame?.(state);
}
return function destroy() {
disposed = true;
state.playing = false;
cancelAnimationFrame(rafId);
ro.disconnect();
canvas.removeEventListener('pointermove', onPointerMove);
canvas.removeEventListener('pointerenter', onPointerEnter);
canvas.removeEventListener('pointerleave', onPointerLeave);
canvas.removeEventListener('pointerdown', onPointerDown);
window.removeEventListener('pointerup', onPointerUp);
effect.destroy?.(state);
};
}
/**
* Starfield — Twinkling stars with optional pointer parallax.
* Category: backgrounds | Animate: true | Interactive: true | Complexity: low
*/
const __effect = function starfield(ctx, state) {
const COUNT = 120;
const COLOR = '255, 255, 255';
let stars = [];
function spawn(width, height) {
return Array.from({ length: COUNT }, () => ({
x: Math.random() * width,
y: Math.random() * height,
r: 0.3 + Math.random() * 1.8,
twinkleSpeed: 0.5 + Math.random() * 2,
twinkleOffset: Math.random() * Math.PI * 2,
parallax: 0.005 + Math.random() * 0.02,
}));
}
stars = spawn(state.width, state.height);
return {
resize({ width, height }) {
stars = spawn(width, height);
},
frame({ width, height, time, pointer, reducedMotion }) {
const px = pointer.inside ? pointer.x / width - 0.5 : 0;
const py = pointer.inside ? pointer.y / height - 0.5 : 0;
for (const s of stars) {
const t = reducedMotion ? s.twinkleOffset : time * s.twinkleSpeed + s.twinkleOffset;
const alpha = 0.3 + 0.7 * (0.5 + 0.5 * Math.sin(t));
const ox = reducedMotion ? 0 : px * s.parallax * width * 8;
const oy = reducedMotion ? 0 : py * s.parallax * height * 8;
ctx.beginPath();
ctx.arc(s.x + ox, s.y + oy, s.r, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${COLOR}, ${alpha})`;
ctx.fill();
}
},
destroy() {
stars = [];
},
};
}
const canvas = document.getElementById('canvas-effect');
mountCanvas(canvas, __effect, { animate: true, clear: true });
</script> Details
Animated Interactive Reduced Motion aria-hidden
starsstarfieldtwinkleparallaxdarkspacenight
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| COUNT | number | 120 | Anzahl der Sterne auf dem Canvas |
Jeder Stern hat eine eigene Twinkle-Frequenz und -Phase via Sinus-Funktion für natürliche Variation. Pointer-Parallax verschiebt Sterne proportional zu ihrer zufälligen Tiefen-Komponente (parallax), was eine glaubwürdige 3D-Tiefe erzeugt. Bei reducedMotion sind alle Sterne statisch sichtbar — kein Twinkle, kein Parallax.