-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgalaxy.js
More file actions
8529 lines (8130 loc) · 406 KB
/
Copy pathgalaxy.js
File metadata and controls
8529 lines (8130 loc) · 406 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! GalaxyJS v3.3 "Deep Field" — galaxy.js
* A zero-dependency cosmic animation + UI component library.
* Unified API: Galaxy.create(type, target, options) · Galaxy.scrollScene(stage, config)
* UMD: works as <script>, CommonJS, and (interop) ES import.
* MIT License.
* ------------------------------------------------------------------ */
(function (root, factory) {
if (typeof module === "object" && module.exports) {
module.exports = factory();
} else if (typeof define === "function" && define.amd) {
define([], factory);
} else {
root.Galaxy = factory();
}
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
var VERSION = "3.4.0";
var hasDOM = typeof document !== "undefined";
var prefersReduced =
hasDOM &&
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
/* ============================================================
* Utilities
* ========================================================== */
function resolve(target) {
if (!target) return null;
if (typeof target === "string") return document.querySelector(target);
return target;
}
function rand(min, max) { return min + Math.random() * (max - min); }
function lerp(a, b, t) { return a + (b - a) * t; }
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
function TAU() { return Math.PI * 2; }
function hexToRgb(hex) {
if (typeof hex !== "string") return { r: 124, g: 92, b: 255 };
hex = hex.replace("#", "").trim();
if (hex.length === 3) hex = hex.split("").map(function (c) { return c + c; }).join("");
var n = parseInt(hex, 16);
if (isNaN(n)) return { r: 124, g: 92, b: 255 };
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };
}
function rgba(c, a) { return "rgba(" + c.r + "," + c.g + "," + c.b + "," + a + ")"; }
function emit(node, name, detail) {
try {
if (typeof CustomEvent === "function") node.dispatchEvent(new CustomEvent(name, { detail: detail }));
} catch (e) { /* environments without CustomEvent */ }
}
function mixRgb(a, b, t) {
return { r: Math.round(lerp(a.r, b.r, t)), g: Math.round(lerp(a.g, b.g, t)), b: Math.round(lerp(a.b, b.b, t)) };
}
function paletteOf(opts, fallback) {
var src = opts.colors && opts.colors.length ? opts.colors : fallback;
return src.map(hexToRgb);
}
/* ============================================================
* WebGL2 tier — hand-written GLSL, still zero dependencies.
*
* Canvas 2D remains the default renderer and the fallback. A shader
* animation declares `renderer: "webgl2"` and a fragment shader; the core
* gives it the same lifecycle every 2D animation gets (DPR-clamped resize,
* pointer, off-screen pause, reduced-motion still frame). Geometry is a
* single full-screen triangle generated from gl_VertexID, so there is no
* vertex buffer to allocate and nothing to leak.
* ========================================================== */
var GL_VERT =
"#version 300 es\n" +
"void main(){vec2 p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));gl_Position=vec4(p*2.0-1.0,0.0,1.0);}";
var GL_TYPES = ["float", "vec2", "vec3", "vec4"];
function glArity(v) { return typeof v === "number" ? 1 : v.length; }
function glCompile(gl, type, src) {
var sh = gl.createShader(type);
if (!sh) return null;
gl.shaderSource(sh, src);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
// A lost context reports every compile as failed with a null log; that is
// not a shader error, so do not report it as one.
if (!gl.isContextLost() && typeof console !== "undefined") {
console.error("GalaxyJS: shader compile failed\n" + gl.getShaderInfoLog(sh));
}
gl.deleteShader(sh);
return null;
}
return sh;
}
/* Builds a program for `fragment`, declaring uniforms from the arity of the
* values in `uniforms` so a shader never has to restate its own signature. */
function glProgram(gl, fragment, uniforms) {
var decls = "";
for (var k in uniforms) {
if (Object.prototype.hasOwnProperty.call(uniforms, k)) {
decls += "uniform " + GL_TYPES[glArity(uniforms[k]) - 1] + " " + k + ";\n";
}
}
var src =
"#version 300 es\nprecision highp float;\n" +
"uniform vec2 uResolution;\nuniform float uTime;\nuniform vec3 uMouse;\n" +
decls + "out vec4 fragColor;\n" + fragment;
var vs = glCompile(gl, gl.VERTEX_SHADER, GL_VERT);
var fs = glCompile(gl, gl.FRAGMENT_SHADER, src);
if (!vs || !fs) return null;
var pr = gl.createProgram();
gl.attachShader(pr, vs); gl.attachShader(pr, fs); gl.linkProgram(pr);
gl.deleteShader(vs); gl.deleteShader(fs);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) {
if (!gl.isContextLost() && typeof console !== "undefined") {
console.error("GalaxyJS: shader link failed\n" + gl.getProgramInfoLog(pr));
}
gl.deleteProgram(pr);
return null;
}
return pr;
}
function glSetUniform(gl, loc, v) {
if (loc === null) return;
if (typeof v === "number") gl.uniform1f(loc, v);
else if (v.length === 2) gl.uniform2f(loc, v[0], v[1]);
else if (v.length === 3) gl.uniform3f(loc, v[0], v[1], v[2]);
else gl.uniform4f(loc, v[0], v[1], v[2], v[3]);
}
/* A still poster — a GPU surface must never degrade to an empty box.
* Shaders and three.js scenes may supply a richer `fallback`.
*
* This runs in two situations, and only one of them has a 2D context:
* - the browser gave us no WebGL2 at all, so the canvas is 2D → paint it;
* - the context is alive but the content failed (a shader that would not
* compile, three.js that would not load) → the canvas is already a WebGL
* canvas and can never hand back a 2D context, so paint the *host*
* element with the equivalent CSS gradient instead.
* Reaching for h.ctx unconditionally is how this used to throw. */
function glPosterFallback(h) {
var pal = paletteOf(h.opts, ["#7c5cff", "#22d3ee"]);
var bg = h.opts.background || "#05060f";
var painted = false;
return {
draw: function () {
if (h.ctx) {
var c = h.ctx, w = h.width, hh = h.height;
c.fillStyle = bg;
c.fillRect(0, 0, w, hh);
var g = c.createRadialGradient(w * 0.5, hh * 0.5, 0, w * 0.5, hh * 0.5, Math.max(w, hh) * 0.7);
g.addColorStop(0, rgba(pal[0], 0.55));
g.addColorStop(1, rgba(pal[pal.length - 1], 0));
c.fillStyle = g;
c.fillRect(0, 0, w, hh);
return;
}
if (painted) return; // a CSS poster is static; set it once
painted = true;
h.el.style.background =
"radial-gradient(60% 60% at 50% 50%, " + rgba(pal[0], 0.55) + " 0%, " +
rgba(pal[pal.length - 1], 0) + " 100%), " + bg;
if (h.gl && !h.gl.isContextLost()) {
var b = hexToRgb(bg);
h.gl.clearColor(b[0] / 255, b[1] / 255, b[2] / 255, 0);
h.gl.clear(h.gl.COLOR_BUFFER_BIT);
}
},
destroy: function () {
if (painted) h.el.style.background = "";
},
};
}
/* Sugar over registerAnimation for a full-screen fragment shader.
* `uniforms(opts, host)` returns plain numbers / arrays, re-read every frame,
* so changing an option never recompiles the program. */
function registerShader(name, def) {
registerAnimation(name, {
renderer: "webgl2",
defaults: def.defaults || {},
fallback: def.fallback || null,
setup: function (h) {
var gl = h.gl;
var vals = def.uniforms ? def.uniforms(h.opts, h) : {};
var prog = glProgram(gl, def.fragment, vals);
if (!prog) return glPosterFallback(h);
var locs = {};
function loc(n) {
if (!(n in locs)) locs[n] = gl.getUniformLocation(prog, n);
return locs[n];
}
gl.useProgram(prog);
return {
draw: function (t) {
if (gl.isContextLost()) return;
gl.useProgram(prog);
gl.uniform2f(loc("uResolution"), h.canvas.width, h.canvas.height);
gl.uniform1f(loc("uTime"), def.staticTime !== undefined && h.reduced ? def.staticTime : t);
gl.uniform3f(
loc("uMouse"),
h.mouse.x * h.dpr,
(h.height - h.mouse.y) * h.dpr,
h.mouse.active ? 1 : 0
);
var u = def.uniforms ? def.uniforms(h.opts, h) : {};
for (var k in u) {
if (Object.prototype.hasOwnProperty.call(u, k)) glSetUniform(gl, loc(k), u[k]);
}
gl.drawArrays(gl.TRIANGLES, 0, 3);
},
destroy: function () {
// Never call WEBGL_lose_context here: a canvas returns the same
// context object on every getContext, so losing it would poison any
// later mount on that canvas.
if (prog && !gl.isContextLost()) gl.deleteProgram(prog);
},
};
},
});
}
/* ============================================================
* three.js tier — optional, lazy, and never required.
*
* The library's contract is zero *required* dependencies, and that does not
* change here. A scene that wants a real scene graph — meshes, PBR materials,
* render targets, a post-processing chain — declares `renderer: "three"`.
* three.js is then fetched once, on demand, the first time such a scene
* mounts. A page that never uses one downloads nothing extra; a page that
* cannot reach the CDN at all still paints the 2D poster rather than an empty
* box, exactly like the WebGL2 tier degrades.
*
* To skip the network entirely, hand the library your own copy:
* import * as THREE from "three";
* Galaxy.useThree(THREE);
* ...or point one scene somewhere else with `{ threeUrl: "/vendor/three.js" }`.
* ========================================================== */
var THREE_URL = "https://cdn.jsdelivr.net/npm/three@0.185.1/build/three.module.min.js";
var threeMod = null; // the resolved namespace, once we have it
var threeWait = null; // the in-flight load, shared by every scene on the page
function loadThree(url) {
if (threeMod) return Promise.resolve(threeMod);
if (threeWait) return threeWait;
// A classic-script dynamic import: no bundler required, and nothing is
// requested until a three-tier scene is actually mounted.
threeWait = Promise.resolve()
.then(function () { return import(/* webpackIgnore: true */ url || THREE_URL); })
.then(function (m) { threeMod = m; return m; })
.catch(function (e) { threeWait = null; throw e; });
return threeWait;
}
/* Sugar over registerAnimation for a three.js scene.
*
* `scene(THREE, host)` runs only once three.js is available and returns the
* same little object every animation returns: { draw, resize?, update?,
* destroy? }. Until then — and forever, if the load fails — the poster draws,
* so `setup` can still answer synchronously like every other renderer. */
function registerThree(name, def) {
registerAnimation(name, {
renderer: "three",
defaults: def.defaults || {},
fallback: def.fallback || null,
setup: function (h) {
var poster = (def.fallback || glPosterFallback)(h);
var live = null;
var dead = false;
// The first resize lands before three.js arrives, so remember it.
var size = { w: h.width, h: h.height };
loadThree(h.opts.threeUrl)
.then(function (T) {
if (dead) return;
live = def.scene(T, h);
// Hand the surface over: drop anything the poster painted first.
if (poster.destroy) poster.destroy();
if (live.resize) live.resize(size.w, size.h);
// Under prefers-reduced-motion the core already drew its one frame
// (the poster). Now that the real scene exists, draw its still frame.
if (h.reduced) live.draw(def.staticTime !== undefined ? def.staticTime : 0, 0);
})
.catch(function (e) {
live = null;
if (typeof console !== "undefined") {
console.warn('GalaxyJS: "' + name + '" needs three.js; showing the still fallback.', e && e.message ? e.message : e);
}
});
return {
draw: function (t, dt) {
if (h.gl && h.gl.isContextLost()) return;
(live || poster).draw(t, dt);
},
resize: function (w, hh) {
size.w = w; size.h = hh;
var target = live || poster;
if (target.resize) target.resize(w, hh);
},
update: function (opts) {
if (live && live.update) live.update(opts);
},
destroy: function () {
dead = true;
// Never force a context loss — see the note in the WebGL2 tier.
if (live && live.destroy) live.destroy();
else if (poster.destroy) poster.destroy();
live = null;
},
};
},
});
}
/* Every three scene needs the same renderer wiring, and getting the pixel
* ratio wrong here is what makes a scene look soft. The core already sized
* the canvas to width*dpr, so setSize must not touch style or recompute it. */
function threeRenderer(T, h) {
var r = new T.WebGLRenderer({
canvas: h.canvas,
context: h.gl,
antialias: false,
alpha: true,
premultipliedAlpha: true,
});
r.setPixelRatio(h.dpr);
r.setSize(h.width, h.height, false);
if ("outputColorSpace" in r) r.outputColorSpace = T.SRGBColorSpace;
r.toneMapping = T.ACESFilmicToneMapping;
r.toneMappingExposure = 1;
return r;
}
/* Frees GPU memory for a scene graph without touching the context. */
function threeDispose(root, extra) {
if (root && root.traverse) {
root.traverse(function (o) {
if (o.geometry && o.geometry.dispose) o.geometry.dispose();
var m = o.material;
if (!m) return;
(Array.isArray(m) ? m : [m]).forEach(function (mm) {
for (var k in mm) {
if (mm[k] && mm[k].isTexture && mm[k].dispose) mm[k].dispose();
}
if (mm.dispose) mm.dispose();
});
});
}
(extra || []).forEach(function (o) { if (o && o.dispose) o.dispose(); });
}
/* ============================================================
* Shared animation loop (one rAF for the whole page)
* ========================================================== */
var Loop = (function () {
var tickers = [];
var raf = null;
function frame(now) {
for (var i = 0; i < tickers.length; i++) {
var t = tickers[i];
if (t.running) { try { t.fn(now); } catch (e) { /* keep loop alive */ } }
}
raf = requestAnimationFrame(frame);
}
return {
add: function (t) {
tickers.push(t);
if (raf === null && hasDOM) raf = requestAnimationFrame(frame);
},
remove: function (t) {
var i = tickers.indexOf(t);
if (i >= 0) tickers.splice(i, 1);
if (!tickers.length && raf !== null) { cancelAnimationFrame(raf); raf = null; }
},
};
})();
/* ============================================================
* Animation registry + surface mounting
* ========================================================== */
var animations = {};
function registerAnimation(name, def) {
animations[name] = {
setup: def.setup,
defaults: def.defaults || {},
renderer: def.renderer || "2d",
fallback: def.fallback || null,
};
}
function mountAnimation(name, target, options) {
var el = resolve(target);
if (!el) throw new Error('GalaxyJS: target not found for "' + name + '"');
var def = animations[name];
if (!def) throw new Error('GalaxyJS: unknown animation "' + name + '"');
el.classList.add("gx-surface-host");
var canvas = document.createElement("canvas");
canvas.className = "gx-canvas";
el.appendChild(canvas);
var opts = Object.assign({}, def.defaults, options || {});
// A shader or three.js animation asks for WebGL2; if the browser cannot
// give one, the surface silently becomes a 2D poster rather than an empty
// canvas. (three.js renders into this same context — see threeRenderer.)
var gl = null, ctx = null, setup = def.setup;
if (def.renderer === "webgl2" || def.renderer === "three") {
try {
gl = canvas.getContext("webgl2", {
alpha: true, antialias: false, premultipliedAlpha: true, powerPreference: "low-power",
});
} catch (e) { gl = null; }
if (!gl) setup = def.fallback || glPosterFallback;
}
if (!gl) ctx = canvas.getContext("2d");
var host = {
el: el, canvas: canvas, ctx: ctx, gl: gl, opts: opts,
width: 1, height: 1, dpr: 1,
mouse: { x: -9999, y: -9999, active: false },
reduced: prefersReduced,
t: 0,
};
var instance = setup(host);
function resize() {
var r = el.getBoundingClientRect();
host.width = Math.max(1, Math.round(r.width));
host.height = Math.max(1, Math.round(r.height));
host.dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.round(host.width * host.dpr);
canvas.height = Math.round(host.height * host.dpr);
canvas.style.width = host.width + "px";
canvas.style.height = host.height + "px";
if (gl) gl.viewport(0, 0, canvas.width, canvas.height);
else ctx.setTransform(host.dpr, 0, 0, host.dpr, 0, 0);
if (instance.resize) instance.resize(host.width, host.height);
}
// Pointer tracking
function onMove(e) {
var r = el.getBoundingClientRect();
var p = e.touches ? e.touches[0] : e;
host.mouse.x = p.clientX - r.left;
host.mouse.y = p.clientY - r.top;
host.mouse.active = true;
}
function onLeave() { host.mouse.active = false; host.mouse.x = -9999; host.mouse.y = -9999; }
if (opts.interactive) {
canvas.setAttribute("data-interactive", "true");
el.addEventListener("pointermove", onMove);
el.addEventListener("pointerleave", onLeave);
}
resize();
var last = (typeof performance !== "undefined" ? performance.now() : Date.now());
var ticker = {
running: false,
fn: function (now) {
var dt = Math.min(0.05, (now - last) / 1000);
last = now;
host.t += dt;
instance.draw(host.t, dt);
},
};
// Resize + visibility observers
var ro = null, io = null, paused = false;
if (typeof ResizeObserver !== "undefined") {
ro = new ResizeObserver(resize);
ro.observe(el);
} else if (hasDOM) {
window.addEventListener("resize", resize);
}
function start() {
if (prefersReduced) { instance.draw(0, 0); return controller; }
if (ticker.running) return controller;
ticker.running = true;
last = (typeof performance !== "undefined" ? performance.now() : Date.now());
Loop.add(ticker);
return controller;
}
function stop() { ticker.running = false; Loop.remove(ticker); return controller; }
// Pause when off-screen (battery / perf friendly)
if (typeof IntersectionObserver !== "undefined" && !prefersReduced) {
io = new IntersectionObserver(function (entries) {
var visible = entries[0].isIntersecting;
if (visible && !paused) start();
else { paused = false; if (!visible) stop(); }
}, { threshold: 0.01 });
io.observe(el);
}
var controller = {
el: el, canvas: canvas, type: name,
start: start,
stop: stop,
pause: function () { stop(); paused = true; return controller; },
resume: function () { paused = false; start(); return controller; },
update: function (next) {
Object.assign(host.opts, next || {});
if (instance.update) instance.update(host.opts);
else if (instance.resize) instance.resize(host.width, host.height);
if (prefersReduced) instance.draw(host.t, 0);
return controller;
},
options: function () { return host.opts; },
destroy: function () {
stop();
if (ro) ro.disconnect();
if (io) io.disconnect();
if (opts.interactive) {
el.removeEventListener("pointermove", onMove);
el.removeEventListener("pointerleave", onLeave);
}
if (instance.destroy) instance.destroy();
if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
el.classList.remove("gx-surface-host");
},
};
if (opts.autoplay !== false) start();
return controller;
}
/* ============================================================
* Built-in animations
* ========================================================== */
function fade(host, alpha) {
var c = host.ctx;
if (host.opts.trail === false || alpha <= 0) {
c.clearRect(0, 0, host.width, host.height);
} else {
c.fillStyle = rgba(hexToRgb(host.opts.background || "#05060f"), alpha);
c.fillRect(0, 0, host.width, host.height);
}
}
// 1. Starfield — drifting parallax stars with twinkle
registerAnimation("starfield", {
defaults: { count: 160, speed: 1, colors: ["#ffffff", "#bcd4ff", "#fff1c4"], background: "#05060f", trail: false },
setup: function (h) {
var stars = [];
function build() {
stars = [];
var area = h.width * h.height;
var n = Math.max(40, Math.round((h.opts.count * area) / (1280 * 720)));
var pal = paletteOf(h.opts, ["#ffffff"]);
for (var i = 0; i < n; i++) {
stars.push({
x: Math.random() * h.width, y: Math.random() * h.height,
z: Math.random(), r: rand(0.4, 1.8),
tw: rand(0, TAU()), col: pal[(Math.random() * pal.length) | 0],
});
}
}
build();
return {
resize: build,
draw: function (t, dt) {
fade(h, 1); var c = h.ctx;
for (var i = 0; i < stars.length; i++) {
var s = stars[i];
s.y += (0.15 + s.z * 0.9) * h.opts.speed * 30 * dt;
if (s.y > h.height + 2) { s.y = -2; s.x = Math.random() * h.width; }
var a = 0.5 + 0.5 * Math.sin(t * (1 + s.z) + s.tw);
c.beginPath();
c.fillStyle = rgba(s.col, 0.25 + a * 0.6);
c.arc(s.x, s.y, s.r * (0.6 + s.z), 0, TAU());
c.fill();
}
},
};
},
});
// 2. Warp speed — hyperspace streaks from the center
registerAnimation("warp", {
defaults: { count: 220, speed: 1, colors: ["#ffffff", "#9bd0ff", "#c9b8ff"], background: "#03040d", trail: true },
setup: function (h) {
var stars = [], cx = 0, cy = 0;
function mk() { return { a: rand(0, TAU()), d: rand(0, 1), len: 0, col: pal[(Math.random() * pal.length) | 0] }; }
var pal;
function build() {
pal = paletteOf(h.opts, ["#ffffff"]); cx = h.width / 2; cy = h.height / 2;
stars = []; for (var i = 0; i < h.opts.count; i++) stars.push(mk());
}
build();
return {
resize: build,
draw: function (t, dt) {
fade(h, 0.28); var c = h.ctx;
var maxR = Math.hypot(cx, cy);
for (var i = 0; i < stars.length; i++) {
var s = stars[i];
var prev = s.d;
s.d += dt * (0.25 + s.d) * h.opts.speed * 1.6;
if (s.d > 1) { s.d = rand(0, 0.15); s.a = rand(0, TAU()); prev = s.d; }
var r1 = prev * maxR, r2 = s.d * maxR;
var x1 = cx + Math.cos(s.a) * r1, y1 = cy + Math.sin(s.a) * r1;
var x2 = cx + Math.cos(s.a) * r2, y2 = cy + Math.sin(s.a) * r2;
c.strokeStyle = rgba(s.col, clamp(s.d, 0.1, 1));
c.lineWidth = lerp(0.4, 2.4, s.d);
c.beginPath(); c.moveTo(x1, y1); c.lineTo(x2, y2); c.stroke();
}
},
};
},
});
// 3. Black hole — accretion disk + lensing glow
registerAnimation("blackHole", {
defaults: { radius: 0.18, speed: 1, colors: ["#ff7b00", "#ffd166", "#7c5cff"], background: "#04040c", particles: 220 },
setup: function (h) {
var disk = [], cx, cy, R, pal;
function build() {
pal = paletteOf(h.opts, ["#ff7b00", "#ffd166"]);
cx = h.width / 2; cy = h.height / 2;
R = Math.min(h.width, h.height) * h.opts.radius;
disk = [];
for (var i = 0; i < h.opts.particles; i++) {
disk.push({ a: rand(0, TAU()), r: rand(R * 1.1, R * 3.4), s: rand(0.4, 1.2), col: pal[(Math.random() * pal.length) | 0] });
}
}
build();
return {
resize: build,
draw: function (t, dt) {
fade(h, 0.22); var c = h.ctx;
// outer glow
var g = c.createRadialGradient(cx, cy, R * 0.6, cx, cy, R * 3.6);
g.addColorStop(0, rgba(pal[0], 0.18));
g.addColorStop(1, "rgba(0,0,0,0)");
c.fillStyle = g; c.beginPath(); c.arc(cx, cy, R * 3.6, 0, TAU()); c.fill();
// disk particles (perspective squash)
for (var i = 0; i < disk.length; i++) {
var p = disk[i];
p.a += dt * h.opts.speed * (1.6 / (p.r / R)) * 0.5;
var x = cx + Math.cos(p.a) * p.r;
var y = cy + Math.sin(p.a) * p.r * 0.38;
var depth = 0.5 + 0.5 * Math.sin(p.a);
c.fillStyle = rgba(p.col, 0.25 + depth * 0.55);
c.beginPath(); c.arc(x, y, p.s * (0.6 + depth), 0, TAU()); c.fill();
}
// event horizon
c.fillStyle = "#000"; c.beginPath(); c.arc(cx, cy, R, 0, TAU()); c.fill();
c.strokeStyle = rgba(pal[pal.length - 1] || pal[0], 0.5);
c.lineWidth = 2; c.beginPath(); c.arc(cx, cy, R * 1.04, 0, TAU()); c.stroke();
},
};
},
});
// 4. Nebula — drifting layered colored clouds
registerAnimation("nebula", {
defaults: { count: 7, speed: 1, colors: ["#7c5cff", "#22d3ee", "#f472b6", "#3b82f6"], background: "#05060f", blur: 60 },
setup: function (h) {
var blobs = [], pal;
function build() {
pal = paletteOf(h.opts, ["#7c5cff", "#22d3ee"]);
blobs = [];
for (var i = 0; i < h.opts.count; i++) {
blobs.push({
x: Math.random(), y: Math.random(),
r: rand(0.25, 0.6), a: rand(0, TAU()),
vx: rand(-0.02, 0.02), vy: rand(-0.02, 0.02),
col: pal[i % pal.length],
});
}
}
build();
return {
resize: build,
draw: function (t, dt) {
var c = h.ctx; c.clearRect(0, 0, h.width, h.height);
c.fillStyle = rgba(hexToRgb(h.opts.background), 1); c.fillRect(0, 0, h.width, h.height);
c.globalCompositeOperation = "lighter";
var minDim = Math.min(h.width, h.height);
for (var i = 0; i < blobs.length; i++) {
var b = blobs[i];
b.x += b.vx * h.opts.speed * dt; b.y += b.vy * h.opts.speed * dt;
if (b.x < -0.2 || b.x > 1.2) b.vx *= -1;
if (b.y < -0.2 || b.y > 1.2) b.vy *= -1;
var px = b.x * h.width, py = b.y * h.height;
var rad = b.r * minDim * (0.9 + 0.1 * Math.sin(t * 0.6 + i));
var g = c.createRadialGradient(px, py, 0, px, py, rad);
g.addColorStop(0, rgba(b.col, 0.5));
g.addColorStop(0.5, rgba(b.col, 0.16));
g.addColorStop(1, "rgba(0,0,0,0)");
c.fillStyle = g; c.beginPath(); c.arc(px, py, rad, 0, TAU()); c.fill();
}
c.globalCompositeOperation = "source-over";
},
};
},
});
// 5. Spiral galaxy — rotating logarithmic arms
registerAnimation("spiral", {
defaults: { stars: 600, arms: 3, speed: 1, colors: ["#ffffff", "#9bd0ff", "#c9b8ff", "#ffd6a5"], background: "#04040c" },
setup: function (h) {
var pts = [], cx, cy, pal;
function build() {
pal = paletteOf(h.opts, ["#ffffff", "#9bd0ff"]);
cx = h.width / 2; cy = h.height / 2;
pts = [];
var maxR = Math.min(h.width, h.height) * 0.46;
for (var i = 0; i < h.opts.stars; i++) {
var arm = i % h.opts.arms;
var d = Math.pow(Math.random(), 0.6);
var r = d * maxR;
var spin = d * 4.2;
var a = (arm / h.opts.arms) * TAU() + spin + rand(-0.18, 0.18);
pts.push({ r: r, a: a, s: rand(0.4, 1.6), col: pal[(Math.random() * pal.length) | 0], tw: rand(0, TAU()) });
}
}
build();
return {
resize: build,
draw: function (t, dt) {
fade(h, 0.25); var c = h.ctx;
var g = c.createRadialGradient(cx, cy, 0, cx, cy, Math.min(h.width, h.height) * 0.2);
g.addColorStop(0, "rgba(255,240,210,0.5)"); g.addColorStop(1, "rgba(0,0,0,0)");
c.fillStyle = g; c.beginPath(); c.arc(cx, cy, Math.min(h.width, h.height) * 0.2, 0, TAU()); c.fill();
var rot = t * 0.12 * h.opts.speed;
for (var i = 0; i < pts.length; i++) {
var p = pts[i];
var a = p.a + rot * (1 - p.r / (Math.min(h.width, h.height) * 0.5) * 0.3);
var x = cx + Math.cos(a) * p.r, y = cy + Math.sin(a) * p.r * 0.62;
var tw = 0.6 + 0.4 * Math.sin(t * 2 + p.tw);
c.fillStyle = rgba(p.col, 0.3 + tw * 0.6);
c.beginPath(); c.arc(x, y, p.s, 0, TAU()); c.fill();
}
},
};
},
});
// 6. Meteor shower — diagonal shooting stars
registerAnimation("meteors", {
defaults: { count: 18, speed: 1, angle: 28, colors: ["#ffffff", "#a5c8ff"], background: "#05060f", stars: true },
setup: function (h) {
var meteors = [], bg = [], pal;
function mk() {
return { x: rand(-0.2, 1) * h.width, y: rand(-1, 0.4) * h.height, len: rand(80, 220), sp: rand(0.6, 1.4), col: pal[(Math.random() * pal.length) | 0] };
}
function build() {
pal = paletteOf(h.opts, ["#ffffff"]);
meteors = []; for (var i = 0; i < h.opts.count; i++) meteors.push(mk());
bg = []; if (h.opts.stars) for (var j = 0; j < 120; j++) bg.push({ x: Math.random() * h.width, y: Math.random() * h.height, r: rand(0.3, 1.2) });
}
build();
var rad = function () { return (h.opts.angle * Math.PI) / 180; };
return {
resize: build,
draw: function (t, dt) {
fade(h, 0.3); var c = h.ctx;
for (var b = 0; b < bg.length; b++) { c.fillStyle = "rgba(255,255,255,0.5)"; c.beginPath(); c.arc(bg[b].x, bg[b].y, bg[b].r, 0, TAU()); c.fill(); }
var ang = rad(), dx = Math.cos(ang), dy = Math.sin(ang);
for (var i = 0; i < meteors.length; i++) {
var m = meteors[i];
var v = m.sp * h.opts.speed * 480 * dt;
m.x += dx * v; m.y += dy * v;
if (m.x > h.width + 50 || m.y > h.height + 50) { meteors[i] = mk(); continue; }
var tx = m.x - dx * m.len, ty = m.y - dy * m.len;
var grad = c.createLinearGradient(m.x, m.y, tx, ty);
grad.addColorStop(0, rgba(m.col, 0.9)); grad.addColorStop(1, "rgba(0,0,0,0)");
c.strokeStyle = grad; c.lineWidth = 2; c.lineCap = "round";
c.beginPath(); c.moveTo(m.x, m.y); c.lineTo(tx, ty); c.stroke();
}
},
};
},
});
// 7. Constellation — connected network, parallax to mouse
registerAnimation("constellation", {
defaults: { count: 90, speed: 1, link: 130, colors: ["#7c5cff", "#22d3ee"], background: "#05060f", interactive: true },
setup: function (h) {
var nodes = [], pal;
function build() {
pal = paletteOf(h.opts, ["#7c5cff", "#22d3ee"]);
var area = h.width * h.height;
var n = Math.max(24, Math.round((h.opts.count * area) / (1280 * 720)));
nodes = [];
for (var i = 0; i < n; i++) nodes.push({ x: Math.random() * h.width, y: Math.random() * h.height, vx: rand(-0.4, 0.4), vy: rand(-0.4, 0.4) });
}
build();
return {
resize: build,
draw: function (t, dt) {
var c = h.ctx; c.clearRect(0, 0, h.width, h.height);
c.fillStyle = rgba(hexToRgb(h.opts.background), 1); c.fillRect(0, 0, h.width, h.height);
var L = h.opts.link;
for (var i = 0; i < nodes.length; i++) {
var p = nodes[i];
p.x += p.vx * h.opts.speed; p.y += p.vy * h.opts.speed;
if (p.x < 0 || p.x > h.width) p.vx *= -1;
if (p.y < 0 || p.y > h.height) p.vy *= -1;
if (h.mouse.active) {
var mdx = p.x - h.mouse.x, mdy = p.y - h.mouse.y, md = Math.hypot(mdx, mdy);
if (md < 140 && md > 0.1) { p.x += (mdx / md) * 0.8; p.y += (mdy / md) * 0.8; }
}
}
for (var a = 0; a < nodes.length; a++) {
for (var b = a + 1; b < nodes.length; b++) {
var dx = nodes[a].x - nodes[b].x, dy = nodes[a].y - nodes[b].y, d = Math.hypot(dx, dy);
if (d < L) {
var alpha = (1 - d / L) * 0.5;
c.strokeStyle = rgba(pal[0], alpha); c.lineWidth = 1;
c.beginPath(); c.moveTo(nodes[a].x, nodes[a].y); c.lineTo(nodes[b].x, nodes[b].y); c.stroke();
}
}
}
for (var k = 0; k < nodes.length; k++) {
c.fillStyle = rgba(pal[1] || pal[0], 0.9);
c.beginPath(); c.arc(nodes[k].x, nodes[k].y, 1.8, 0, TAU()); c.fill();
}
},
};
},
});
// 8. Particle field — interactive cursor repel/attract
registerAnimation("particles", {
defaults: { count: 120, speed: 1, colors: ["#ffffff", "#7c5cff", "#22d3ee"], background: "#05060f", interactive: true, mode: "repel" },
setup: function (h) {
var ps = [], pal;
function build() {
pal = paletteOf(h.opts, ["#ffffff"]);
var area = h.width * h.height;
var n = Math.max(30, Math.round((h.opts.count * area) / (1280 * 720)));
ps = [];
for (var i = 0; i < n; i++) ps.push({ x: Math.random() * h.width, y: Math.random() * h.height, vx: rand(-0.3, 0.3), vy: rand(-0.3, 0.3), r: rand(1, 2.6), col: pal[(Math.random() * pal.length) | 0] });
}
build();
return {
resize: build,
draw: function (t, dt) {
fade(h, 0.2); var c = h.ctx;
var dir = h.opts.mode === "attract" ? -1 : 1;
for (var i = 0; i < ps.length; i++) {
var p = ps[i];
if (h.mouse.active) {
var dx = p.x - h.mouse.x, dy = p.y - h.mouse.y, d = Math.hypot(dx, dy);
if (d < 120 && d > 0.1) { var f = ((120 - d) / 120) * dir * 1.4; p.vx += (dx / d) * f; p.vy += (dy / d) * f; }
}
p.vx *= 0.96; p.vy *= 0.96;
p.x += (p.vx + rand(-0.05, 0.05)) * h.opts.speed; p.y += (p.vy + rand(-0.05, 0.05)) * h.opts.speed;
if (p.x < 0) p.x = h.width; if (p.x > h.width) p.x = 0;
if (p.y < 0) p.y = h.height; if (p.y > h.height) p.y = 0;
c.fillStyle = rgba(p.col, 0.85);
c.beginPath(); c.arc(p.x, p.y, p.r, 0, TAU()); c.fill();
}
},
};
},
});
// 9. Aurora — flowing ribbons of light
registerAnimation("aurora", {
defaults: { bands: 4, speed: 1, colors: ["#22d3ee", "#7c5cff", "#34d399", "#f472b6"], background: "#04060f" },
setup: function (h) {
var pal;
function build() { pal = paletteOf(h.opts, ["#22d3ee", "#7c5cff"]); }
build();
return {
resize: build,
draw: function (t, dt) {
var c = h.ctx; c.clearRect(0, 0, h.width, h.height);
c.fillStyle = rgba(hexToRgb(h.opts.background), 1); c.fillRect(0, 0, h.width, h.height);
c.globalCompositeOperation = "lighter";
for (var b = 0; b < h.opts.bands; b++) {
var col = pal[b % pal.length];
var baseY = (b + 1) / (h.opts.bands + 1) * h.height;
c.beginPath();
for (var x = 0; x <= h.width; x += 8) {
var ph = t * h.opts.speed * 0.6 + b * 1.7;
var y = baseY + Math.sin(x * 0.006 + ph) * 60 + Math.sin(x * 0.013 + ph * 1.4) * 28;
if (x === 0) c.moveTo(x, y); else c.lineTo(x, y);
}
var grad = c.createLinearGradient(0, baseY - 90, 0, baseY + 90);
grad.addColorStop(0, "rgba(0,0,0,0)");
grad.addColorStop(0.5, rgba(col, 0.35));
grad.addColorStop(1, "rgba(0,0,0,0)");
c.lineTo(h.width, h.height); c.lineTo(0, h.height); c.closePath();
c.fillStyle = grad; c.fill();
}
c.globalCompositeOperation = "source-over";
},
};
},
});
// 10. Wormhole — receding tunnel of rings
registerAnimation("wormhole", {
defaults: { rings: 26, speed: 1, colors: ["#7c5cff", "#22d3ee", "#f472b6"], background: "#03030b" },
setup: function (h) {
var cx, cy, pal;
function build() { cx = h.width / 2; cy = h.height / 2; pal = paletteOf(h.opts, ["#7c5cff", "#22d3ee"]); }
build();
return {
resize: build,
draw: function (t, dt) {
fade(h, 0.3); var c = h.ctx;
var maxR = Math.hypot(cx, cy);
for (var i = 0; i < h.opts.rings; i++) {
var prog = ((i / h.opts.rings) + (t * h.opts.speed * 0.12)) % 1;
var r = prog * maxR;
var wob = Math.sin(t * 1.5 + i) * 10 * (1 - prog);
var col = mixRgb(pal[0], pal[1] || pal[0], prog);
c.strokeStyle = rgba(col, (1 - prog) * 0.8);
c.lineWidth = lerp(0.5, 3, 1 - prog);
c.beginPath();
c.ellipse(cx + wob, cy, r, r * 0.8, t * 0.2, 0, TAU());
c.stroke();
}
},
};
},
});
// 11. Orbits — planets circling a star
registerAnimation("orbits", {
defaults: { bodies: 6, speed: 1, colors: ["#ffd166", "#7c5cff", "#22d3ee", "#f472b6", "#34d399"], background: "#05060f" },
setup: function (h) {
var bodies = [], cx, cy, pal;
function build() {
cx = h.width / 2; cy = h.height / 2; pal = paletteOf(h.opts, ["#7c5cff", "#22d3ee"]);
var maxR = Math.min(h.width, h.height) * 0.46;
bodies = [];
for (var i = 0; i < h.opts.bodies; i++) {
bodies.push({ r: lerp(maxR * 0.22, maxR, (i + 1) / h.opts.bodies), a: rand(0, TAU()), sp: rand(0.3, 1) / (i + 1), size: rand(3, 8), col: pal[i % pal.length] });
}
}
build();
return {
resize: build,
draw: function (t, dt) {
var c = h.ctx; c.clearRect(0, 0, h.width, h.height);
c.fillStyle = rgba(hexToRgb(h.opts.background), 1); c.fillRect(0, 0, h.width, h.height);
var g = c.createRadialGradient(cx, cy, 0, cx, cy, 60);
g.addColorStop(0, "rgba(255,224,150,0.9)"); g.addColorStop(1, "rgba(255,180,80,0)");
c.fillStyle = g; c.beginPath(); c.arc(cx, cy, 60, 0, TAU()); c.fill();
for (var i = 0; i < bodies.length; i++) {
var b = bodies[i];
c.strokeStyle = "rgba(255,255,255,0.08)"; c.lineWidth = 1;
c.beginPath(); c.ellipse(cx, cy, b.r, b.r * 0.5, 0, 0, TAU()); c.stroke();
b.a += b.sp * h.opts.speed * dt;
var x = cx + Math.cos(b.a) * b.r, y = cy + Math.sin(b.a) * b.r * 0.5;
c.fillStyle = rgba(b.col, 1);
c.beginPath(); c.arc(x, y, b.size, 0, TAU()); c.fill();
}
},
};
},
});
// 12. Pulsar — rhythmic expanding rings
registerAnimation("pulsar", {
defaults: { speed: 1, colors: ["#22d3ee", "#7c5cff"], background: "#04040c", waves: 4 },
setup: function (h) {
var cx, cy, pal;
function build() { cx = h.width / 2; cy = h.height / 2; pal = paletteOf(h.opts, ["#22d3ee", "#7c5cff"]); }
build();
return {
resize: build,
draw: function (t, dt) {
fade(h, 0.18); var c = h.ctx;
var maxR = Math.min(h.width, h.height) * 0.5;
for (var i = 0; i < h.opts.waves; i++) {
var prog = ((t * h.opts.speed * 0.5) + i / h.opts.waves) % 1;
var r = prog * maxR;
c.strokeStyle = rgba(mixRgb(pal[0], pal[1] || pal[0], prog), (1 - prog) * 0.9);
c.lineWidth = lerp(3, 0.5, prog);
c.beginPath(); c.arc(cx, cy, r, 0, TAU()); c.stroke();
}
var pulse = 6 + Math.abs(Math.sin(t * h.opts.speed * 3)) * 10;
var g = c.createRadialGradient(cx, cy, 0, cx, cy, pulse * 2);
g.addColorStop(0, rgba(pal[0], 1)); g.addColorStop(1, rgba(pal[0], 0));
c.fillStyle = g; c.beginPath(); c.arc(cx, cy, pulse * 2, 0, TAU()); c.fill();
},
};
},
});
// 13. Gradient flow — animated mesh-gradient backdrop
registerAnimation("gradient", {
defaults: { speed: 1, colors: ["#7c5cff", "#22d3ee", "#f472b6", "#05060f"] },
setup: function (h) {
var pal;
function build() { pal = paletteOf(h.opts, ["#7c5cff", "#22d3ee", "#f472b6"]); }
build();
return {