Amazing JavaScript - galaxy animation
javascript

Amazing JavaScript - galaxy animation

Dive into the cosmos with this stunning JavaScript galaxy animation! Watch the stars come alive and let your creativity soar.

amazing-javascript-galaxy-animation.javascript
1<!DOCTYPE html>
2<html lang="en">
3<head>
4<meta charset="UTF-8">
5<title>Spiral Galaxy</title>
6<style>
7  html, body {
8    margin: 0;
9    padding: 0;
10    width: 100%;
11    height: 100%;
12    background: #030308;
13    overflow: hidden;
14  }
15  canvas { display: block; }
16</style>
17</head>
18<body>
19<canvas id="c"></canvas>
20<script>
21const canvas = document.getElementById('c');
22const ctx = canvas.getContext('2d');
23let W, H, DPR, CX, CY;
24
25function resize() {
26  DPR = Math.min(window.devicePixelRatio || 1, 2);
27  W = window.innerWidth;
28  H = window.innerHeight;
29  canvas.width = W * DPR;
30  canvas.height = H * DPR;
31  canvas.style.width = W + 'px';
32  canvas.style.height = H + 'px';
33  ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
34  CX = W / 2;
35  CY = H * 0.46;
36}
37resize();
38window.addEventListener('resize', resize);
39
40// ---- Build galaxy particle field ----
41const N = 5500;
42const ARMS = 3;
43const R_MAX = Math.min(window.innerWidth, window.innerHeight) * 0.72;
44const PITCH = 0.24;
45
46const particles = [];
47for (let i = 0; i < N; i++) {
48  const u = Math.random();
49  let radius = R_MAX * Math.pow(u, 0.55);
50  const armIndex = Math.floor(Math.random() * ARMS);
51  const baseAngle = armIndex * (2 * Math.PI / ARMS) + PITCH * Math.log(radius + 8);
52  const thickness = 0.18 + 0.55 * (radius / R_MAX);
53  const jitter = (Math.random() - 0.5) * 2 * thickness;
54  radius += (Math.random() - 0.5) * 12;
55  radius = Math.max(4, Math.min(R_MAX, radius));
56
57  const omega = 0.42 / (radius / 120 + 0.6); // rad/frame-scaled speed
58
59  const tCol = Math.min(1, radius /

Ready to Level Up?

Stop guessing what to learn next. Get the structured path that separates senior engineers from everyone else.

Grab Your Free Roadmap