# 3D starfield

> Stars fly towards you and leave short trails, like a jump to hyperspace in slow motion.

- Category: [Backgrounds](https://library.aimran.es/components/patterns)
- Built with: HTML + CSS
- Live editor: https://library.aimran.es/blocks/pt-stars
- Library: AIMRAN Library (https://library.aimran.es), free, no sign-up, by Aimran Oukham

## Where to use it

A starfield is a natural match for anything about space, speed or launching: the hero of a startup’s launch page, the intro of a sci-fi game site or the countdown for an online event. Stars stream out from the center, so your eye goes straight to the middle. An animated starfield background on canvas, with a few lines of JS.

At full speed it’s exciting for a few seconds and tiring after a minute, so slow it down on pages people stay on. Lower the opacity too if there’s a form on top, because trails moving behind input fields are distracting.

## Code

### HTML

```html
<div class="pt-stars"><canvas></canvas></div>
```

### CSS

```css
.pt-stars {
  --c1: #8ec5ff;
  --c2: #c4b5fd;
  --c3: #ffffff;
  --k: 1;
  /* velocidad */
  --d: 1;
  /* densidad / escala */
  --o: 1;
  /* opacidad */
  --bg: #05060a;
  --fg: #ffffff;
  --blend: screen;
  min-height: 100vh;
}

.pt-stars {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: var(--bg);
  container-type: size;
  isolation: isolate;
}

.pt-stars>* {
  opacity: var(--o);
}

.pt-stars canvas {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  display: block;
}
```

### JavaScript

```js
(function (el) {
const cv=el.querySelector("canvas"),x=cv.getContext("2d");let W=0,H=0,raf=0;
const fit=()=>{const r=Math.min(window.devicePixelRatio||1,2);W=el.clientWidth;H=el.clientHeight;cv.width=W*r;cv.height=H*r;x.setTransform(r,0,0,r,0,0)};
const ro=new ResizeObserver(fit);ro.observe(el);fit();
const V=()=>{const s=getComputedStyle(el),g=(n)=>s.getPropertyValue(n).trim();return{c1:g("--c1"),c2:g("--c2"),c3:g("--c3"),bg:g("--bg"),k:+g("--k")||1,d:+g("--d")||1}};
// Movimiento reducido: se calculan de golpe unos fotogramas (con tiempo simulado) y la escena se queda quieta
const RM=matchMedia("(prefers-reduced-motion: reduce)").matches;let RF=0;
const requestAnimationFrame=(f)=>{if(!RM)return window.requestAnimationFrame(f);if(++RF<400)f(RF*60);return 0};
const N=900,S=[];for(let i=0;i<N;i++)S.push({x:Math.random()*2-1,y:Math.random()*2-1,z:Math.random()});
const loop=()=>{const v=V(),cols=[v.c1,v.c2,v.c3];x.globalAlpha=.35;x.fillStyle=v.bg;x.fillRect(0,0,W,H);
const n=Math.min(N,Math.floor(320*v.d)),cx=W/2,cy=H/2,f=Math.max(W,H)*.5;
for(let i=0;i<n;i++){const p=S[i],pz=p.z;p.z-=.004*v.k;if(p.z<=.02){p.x=Math.random()*2-1;p.y=Math.random()*2-1;p.z=1;continue}
x.strokeStyle=cols[i%3];x.lineWidth=(1-p.z)*2.6;x.globalAlpha=1-p.z;x.beginPath();x.moveTo(cx+p.x/pz*f*.5,cy+p.y/pz*f*.5);x.lineTo(cx+p.x/p.z*f*.5,cy+p.y/p.z*f*.5);x.stroke()}
x.globalAlpha=1;raf=requestAnimationFrame(loop)};loop();
return()=>{cancelAnimationFrame(raf);ro.disconnect()};
})(document.querySelector(".pt-stars"));
```

### React

```tsx
// @ts-nocheck
import { useEffect, useRef } from "react";

const css = `
.pt-stars {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: var(--bg);
  container-type: size;
  isolation: isolate;
}

.pt-stars>* {
  opacity: var(--o);
}

.pt-stars canvas {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  display: block;
}

`;

export default function PatternStars() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
const cv=el.querySelector("canvas"),x=cv.getContext("2d");let W=0,H=0,raf=0;
const fit=()=>{const r=Math.min(window.devicePixelRatio||1,2);W=el.clientWidth;H=el.clientHeight;cv.width=W*r;cv.height=H*r;x.setTransform(r,0,0,r,0,0)};
const ro=new ResizeObserver(fit);ro.observe(el);fit();
const V=()=>{const s=getComputedStyle(el),g=(n)=>s.getPropertyValue(n).trim();return{c1:g("--c1"),c2:g("--c2"),c3:g("--c3"),bg:g("--bg"),k:+g("--k")||1,d:+g("--d")||1}};
// Movimiento reducido: se calculan de golpe unos fotogramas (con tiempo simulado) y la escena se queda quieta
const RM=matchMedia("(prefers-reduced-motion: reduce)").matches;let RF=0;
const requestAnimationFrame=(f)=>{if(!RM)return window.requestAnimationFrame(f);if(++RF<400)f(RF*60);return 0};
const N=900,S=[];for(let i=0;i<N;i++)S.push({x:Math.random()*2-1,y:Math.random()*2-1,z:Math.random()});
const loop=()=>{const v=V(),cols=[v.c1,v.c2,v.c3];x.globalAlpha=.35;x.fillStyle=v.bg;x.fillRect(0,0,W,H);
const n=Math.min(N,Math.floor(320*v.d)),cx=W/2,cy=H/2,f=Math.max(W,H)*.5;
for(let i=0;i<n;i++){const p=S[i],pz=p.z;p.z-=.004*v.k;if(p.z<=.02){p.x=Math.random()*2-1;p.y=Math.random()*2-1;p.z=1;continue}
x.strokeStyle=cols[i%3];x.lineWidth=(1-p.z)*2.6;x.globalAlpha=1-p.z;x.beginPath();x.moveTo(cx+p.x/pz*f*.5,cy+p.y/pz*f*.5);x.lineTo(cx+p.x/p.z*f*.5,cy+p.y/p.z*f*.5);x.stroke()}
x.globalAlpha=1;raf=requestAnimationFrame(loop)};loop();
return()=>{cancelAnimationFrame(raf);ro.disconnect()};
  }, []);
  return (
    <>
      <style>{css}</style>
      <div
        ref={ref}
        className="pt-stars"
        style={{
          "--c1": "#8ec5ff",
          "--c2": "#c4b5fd",
          "--c3": "#ffffff",
          "--k": 1,
          "--d": 1,
          "--o": 1,
          "--bg": "#05060a",
          "--fg": "#ffffff",
          "--blend": "screen",
          minHeight: "100vh",
        }}
      >
        <canvas></canvas>
      </div>
    </>
  );
}
```

## Prompt for AI assistants

Paste this into ChatGPT, Claude, Cursor, v0 or Lovable to adapt the block to your stack (Tailwind, Vue, Svelte…):

````text
I want to add the “3D starfield” block (Backgrounds) from AIMRAN Library to my project.

## What it is
Stars fly towards you and leave short trails, like a jump to hyperspace in slow motion.

## Chosen settings
- Color 1: #8ec5ff
- Color 2: #c4b5fd
- Color 3: #ffffff
- Speed: 1x (from 0.2 to 3x)
- Density / scale: 1x (from 0.5 to 2x)
- Opacity: 1 (from 0.2 to 1)

## What I need
1. Add it to my project with the same look and animation as the reference code: same sizes, colours, radii, shadows, timings and easing.
2. It is built with plain HTML and CSS (the reference wraps it in a React component with its CSS). If my project uses something else (Vue, Svelte, Astro, plain HTML…), translate it without losing any behaviour. If I use Tailwind, turn the styles into classes; if not, keep the CSS in its own file.
3. Expose the settings above as props (or CSS variables) with those values as defaults.
4. Make it work well on phones: nothing that depends only on hover, touch targets of at least 44 px and no overflow on 320 px screens.
5. Make it look right in light and dark mode.
6. Keep it accessible: semantic HTML, roles and aria-* where needed, visible focus and keyboard support.
7. Respect prefers-reduced-motion: with reduced motion, no big animations but the same end result.

## Reference code
```tsx
// @ts-nocheck
import { useEffect, useRef } from "react";

const css = `
.pt-stars {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: var(--bg);
  container-type: size;
  isolation: isolate;
}

.pt-stars>* {
  opacity: var(--o);
}

.pt-stars canvas {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  display: block;
}

`;

export default function PatternStars() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
const cv=el.querySelector("canvas"),x=cv.getContext("2d");let W=0,H=0,raf=0;
const fit=()=>{const r=Math.min(window.devicePixelRatio||1,2);W=el.clientWidth;H=el.clientHeight;cv.width=W*r;cv.height=H*r;x.setTransform(r,0,0,r,0,0)};
const ro=new ResizeObserver(fit);ro.observe(el);fit();
const V=()=>{const s=getComputedStyle(el),g=(n)=>s.getPropertyValue(n).trim();return{c1:g("--c1"),c2:g("--c2"),c3:g("--c3"),bg:g("--bg"),k:+g("--k")||1,d:+g("--d")||1}};
// Movimiento reducido: se calculan de golpe unos fotogramas (con tiempo simulado) y la escena se queda quieta
const RM=matchMedia("(prefers-reduced-motion: reduce)").matches;let RF=0;
const requestAnimationFrame=(f)=>{if(!RM)return window.requestAnimationFrame(f);if(++RF<400)f(RF*60);return 0};
const N=900,S=[];for(let i=0;i<N;i++)S.push({x:Math.random()*2-1,y:Math.random()*2-1,z:Math.random()});
const loop=()=>{const v=V(),cols=[v.c1,v.c2,v.c3];x.globalAlpha=.35;x.fillStyle=v.bg;x.fillRect(0,0,W,H);
const n=Math.min(N,Math.floor(320*v.d)),cx=W/2,cy=H/2,f=Math.max(W,H)*.5;
for(let i=0;i<n;i++){const p=S[i],pz=p.z;p.z-=.004*v.k;if(p.z<=.02){p.x=Math.random()*2-1;p.y=Math.random()*2-1;p.z=1;continue}
x.strokeStyle=cols[i%3];x.lineWidth=(1-p.z)*2.6;x.globalAlpha=1-p.z;x.beginPath();x.moveTo(cx+p.x/pz*f*.5,cy+p.y/pz*f*.5);x.lineTo(cx+p.x/p.z*f*.5,cy+p.y/p.z*f*.5);x.stroke()}
x.globalAlpha=1;raf=requestAnimationFrame(loop)};loop();
return()=>{cancelAnimationFrame(raf);ro.disconnect()};
  }, []);
  return (
    <>
      <style>{css}</style>
      <div
        ref={ref}
        className="pt-stars"
        style={{
          "--c1": "#8ec5ff",
          "--c2": "#c4b5fd",
          "--c3": "#ffffff",
          "--k": 1,
          "--d": 1,
          "--o": 1,
          "--bg": "#05060a",
          "--fg": "#ffffff",
          "--blend": "screen",
          minHeight: "100vh",
        }}
      >
        <canvas></canvas>
      </div>
    </>
  );
}
```

Give me the complete final code, ready to paste, and tell me in one line where to put it in my project.
````
