-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstell.js
More file actions
851 lines (731 loc) · 29.2 KB
/
Copy pathconstell.js
File metadata and controls
851 lines (731 loc) · 29.2 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
/**
* Constell — animated constellation background
*
* Usage (ESM):
* import { Constell } from './constell.js';
* Constell.init(canvas); // defaults
* Constell.init(canvas, userConfig); // with overrides
* Constell.configure(overrides); // runtime re-config
* Constell.toggleTheme("light" | "dark" | "system"); // switch theme
*/
/* ──────────────────────────────────────────────
Default configuration — all magic numbers live here
────────────────────────────────────────────── */
const DEFAULT_CONFIG = {
star: {
count: 42,
depthMin: 0.18,
depthMax: 1.0,
radiusMin: 0.45,
radiusMax: 2.1,
speedXMin: -0.004,
speedXMax: 0.004,
speedYMin: -0.003,
speedYMax: 0.003,
twinkleSpeedMin: 0.5,
twinkleSpeedMax: 2.2,
hueMin: 198,
hueMax: 236,
},
motion: {
frameMs: 100, // ≈ 10 fps (min ms between frames)
pointerLerp: 0.07, // smoothness of pointer tracking
prefersReducedMotion: false,
speed: 5, // master speed multiplier (1–10, default 5 = normal)
},
parallax: {
sensitivityX: 0.0006,
sensitivityY: 0.00045,
depthFactorX: 0.05, // non-depth parallax on screen coords (X)
depthFactorY: 0.04, // non-depth parallax on screen coords (Y)
},
starMotion: {
driftBase: 0.14,
driftDepthScale: 0.9, // how much depth amplifies drift speed
},
visual: {
alphaBase: 0.18,
alphaDepthScale: 0.55,
glowThreshold: 0.65, // star.depth above which a glow is drawn
glowAlphaMultiplier: 0.55,
glowRadiusMultiplier: 5,
twinkleAmplitude: 0.16,
},
nebula: [
// Layer 1 — slow sine drift + pointer parallax
{
xBase: 0.22,
yBase: 0.24,
radiusScale: 0.42,
color: "rgba(126, 94, 255, 0.18)",
driftX: { enabled: true, freq: 0.4, amount: 0.1 },
driftY: { enabled: true, freq: 0.35, amount: 0.06 },
parallaxX: 0.08,
parallaxY: 0.08,
},
// Layer 2 — inverted sine drift + pointer parallax
{
xBase: 0.82,
yBase: 0.28,
radiusScale: 0.36,
color: "rgba(0, 224, 255, 0.14)",
driftX: { enabled: true, freq: 0.38, amount: 0.08, invert: true },
driftY: { enabled: true, freq: 0.32, amount: 0.06, scale: 0.5 },
parallaxX: 0.05,
parallaxY: 0.05,
},
// Layer 3 — pure sin/cos position animation
{
xBase: 0.52,
yBase: 0.72,
radiusScale: 0.48,
color: "rgba(255, 121, 214, 0.08)",
animatedX: { enabled: true, freq: 0.35, amount: 0.08 },
animatedY: { enabled: true, freq: 0.3, amount: 0.06, type: "cos" },
parallaxX: 0,
parallaxY: 0,
},
],
shootingStar: {
enabled: true,
chancePerFrame: 0.008, // probability of spawning per frame (~1 every 2s at 60fps)
speedMin: 4, // pixels/frame
speedMax: 10,
angleMin: 25, // degrees from horizontal (25-55 = diagonal sweep)
angleMax: 55,
lengthMin: 80, // trail length in px
lengthMax: 200,
thicknessMin: 1.8,
thicknessMax: 3.2,
hueMin: 190, // white-blue range
hueMax: 240,
headAlpha: 0.95,
fadeInFrames: 3, // frames to reach max brightness
lifetimeMin: 25, // frames alive before disappearing
lifetimeMax: 60,
},
theme: "dark", // "dark" | "light" | "system"
backdrop: {
colorTop: "#030510",
colorMid: "#061425",
midStop: 0.55,
},
};
/* ──────────────────────────────────────────────
Theme definitions — each overrides a subset of
DEFAULT_CONFIG; resolved themes are deep-merged.
────────────────────────────────────────────── */
const THEMES = {
dark: {
backdrop: { colorTop: "#030510", colorMid: "#061425" },
star: { hueMin: 198, hueMax: 236 },
nebula: [
{ color: "rgba(126, 94, 255, 0.18)" },
{ color: "rgba(0, 224, 255, 0.14)" },
{ color: "rgba(255, 121, 214, 0.08)" },
],
shootingStar: { hueMin: 190, hueMax: 240 },
},
light: {
backdrop: { colorTop: "#d6e0f0", colorMid: "#eaf0fa" },
star: { hueMin: 210, hueMax: 310 }, // cooler / softer for light bg
visual: {
alphaBase: 0.55, // Much higher so stars visible on bright bg
glowThreshold: 1.0, // Effectively disables glows (pointless on light bg)
glowAlphaMultiplier: 0,
twinkleAmplitude: 0.12,
},
nebula: [
{ color: "rgba(145, 130, 240, 0.48)" }, // lighter purple
{ color: "rgba(40, 120, 220, 0.45)" }, // deep blue
{ color: "rgba(255, 170, 80, 0.38)" }, // lighter orange
],
shootingStar: {
hueMin: 38,
hueMax: 52,
headAlpha: 0.95,
lengthMin: 100,
lengthMax: 240,
thicknessMin: 2.5,
thicknessMax: 4.0,
},
},
};
/* ──────────────────────────────────────────────
Config helpers — deep merge with defaults + theme resolution
────────────────────────────────────────────── */
/**
* Deep-merge a theme definition into DEFAULT_CONFIG.
* Returns a new config object with the theme applied as base.
* @param {string} themeName — resolved theme key ("dark" | "light")
* @param {string} [retainMode] — original theme mode (e.g. "system" to preserve) or undefined
*/
function applyTheme(themeName, retainMode) {
if (!themeName || !THEMES[themeName]) {
const cfg = structuredClone(DEFAULT_CONFIG);
if (retainMode !== undefined) cfg.theme = retainMode;
return cfg;
}
const cfg = structuredClone(DEFAULT_CONFIG);
const th = THEMES[themeName];
for (const key of ["star", "motion", "parallax", "visual"]) {
if (key in th && typeof th[key] === "object") {
Object.assign(cfg[key], th[key]);
}
}
if (Array.isArray(th.nebula)) {
for (let i = 0; i < th.nebula.length; i++) {
if (i < cfg.nebula.length && typeof th.nebula[i] === "object") {
Object.assign(cfg.nebula[i], th.nebula[i]);
}
}
}
if (th.shootingStar && typeof th.shootingStar === "object") {
Object.assign(cfg.shootingStar, th.shootingStar);
}
if (th.backdrop && typeof th.backdrop === "object") {
Object.assign(cfg.backdrop, th.backdrop);
}
// Set resolved theme name, but preserve original mode (e.g. "system")
cfg.theme = retainMode != null ? retainMode : themeName;
return cfg;
}
/**
* Resolve the effective theme name from config.
* "system" → detects prefers-color-scheme.
*/
function resolveTheme(config) {
const raw = config.theme || "dark";
if (raw === "system") {
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
return raw;
}
/**
* Deep-merge a user config over the defaults (shallow on first level,
* merges star / motion / parallax / visual / nebula sub-objects),
* with theme resolution applied.
*/
function mergeConfig(user) {
// Resolve the effective theme, preserving any mode the user wants to keep
const effectiveTheme = (user && user.theme !== undefined) ? user.theme : config.theme;
const resolvedTheme = resolveTheme({ theme: effectiveTheme });
const cfg = applyTheme(resolvedTheme, effectiveTheme); // pass through original mode
if (!user) return cfg;
// Merge top-level known groups
for (const key of ["star", "motion", "parallax", "visual"]) {
if (key in user && typeof user[key] === "object") {
Object.assign(cfg[key], user[key]);
} else if (key in user) {
cfg[key] = user[key]; // replace entirely (rare)
}
}
// Nebula array: shallow-merge each slot by index
if (Array.isArray(user.nebula)) {
for (let i = 0; i < user.nebula.length; i++) {
if (i < cfg.nebula.length && typeof user.nebula[i] === "object") {
Object.assign(cfg.nebula[i], user.nebula[i]);
} else {
cfg.nebula[i] = structuredClone(user.nebula[i]);
}
}
}
// Shooting star
if (user.shootingStar && typeof user.shootingStar === "object") {
Object.assign(cfg.shootingStar, user.shootingStar);
}
// Backdrop
if (user.backdrop && typeof user.backdrop === "object") {
Object.assign(cfg.backdrop, user.backdrop);
}
return cfg;
}
/* ──────────────────────────────────────────────
Module state
────────────────────────────────────────────── */
let canvas, context;
let config = DEFAULT_CONFIG; // live (merged) config
let stars = [];
let shootingStars = []; // active shooting star instances
let pointer = { x: 0.5, y: 0.5, targetX: 0.5, targetY: 0.5 };
let width = 0,
height = 0,
dpr = 1;
let lastFrameTime = 0;
let animationId = null;
let initialized = false;
// Dark-mode media query listener for "system" theme switching
const _darkQuery = window.matchMedia("(prefers-color-scheme: dark)");
_darkQuery.addEventListener?.("change", onSystemThemeChange);
function onSystemThemeChange() {
if (!initialized) return;
if (config.theme !== "system") return;
const newCfg = mergeConfig({}); // re-resolve theme from current config
Object.assign(config, newCfg);
}
/* ──────────────────────────────────────────────
Math helpers (kept as bare functions for perf)
────────────────────────────────────────────── */
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function lerp(from, to, amount) {
return from + (to - from) * amount;
}
function random(min, max) {
return min + Math.random() * (max - min);
}
/* ──────────────────────────────────────────────
Star lifecycle
────────────────────────────────────────────── */
function createStar() {
const s = config.star;
return {
x: Math.random(),
y: Math.random(),
depth: random(s.depthMin, s.depthMax),
radius: random(s.radiusMin, s.radiusMax),
speedX: random(s.speedXMin, s.speedXMax),
speedY: random(s.speedYMin, s.speedYMax),
twinkleSpeed: random(s.twinkleSpeedMin, s.twinkleSpeedMax),
phase: Math.random() * Math.PI * 2,
hue: random(s.hueMin, s.hueMax),
screenX: 0,
screenY: 0,
twinkle: 1,
};
}
function seedStars() {
stars.length = 0;
for (let i = 0; i < config.star.count; i++) {
stars.push(createStar());
}
}
/* ──────────────────────────────────────────────
Canvas sizing
────────────────────────────────────────────── */
function resize() {
dpr = 1;
width = window.innerWidth;
height = window.innerHeight;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
context.setTransform(dpr, 0, 0, dpr, 0, 0);
}
/* ──────────────────────────────────────────────
Drawing — backdrop (gradient + nebulae)
────────────────────────────────────────────── */
function drawBackdrop(time) {
const c = config;
const speed = c.motion.speed / 5; // normalise around default of 5
const px = pointer.x * width;
const py = pointer.y * height;
// ── Gradient background ──
const grad = context.createLinearGradient(0, 0, width, height);
grad.addColorStop(0, c.backdrop.colorTop);
grad.addColorStop(c.backdrop.midStop, c.backdrop.colorMid);
grad.addColorStop(1, c.backdrop.colorTop);
context.fillStyle = grad;
context.fillRect(0, 0, width, height);
// ── Nebula layers ──
context.save();
// screen brightens (dark bg); darken/normal darkens (light bg)
const blendMode = config.theme === "system"
? (resolveTheme(config) === "light" ? "darken" : "screen")
: (config.theme === "light" ? "darken" : "screen");
context.globalCompositeOperation = blendMode;
for (const layer of c.nebula) {
const t = time;
let offsetX = 0,
offsetY = 0;
// Drift-based movement (sine waves) — time scaled by speed
if (layer.driftX?.enabled) {
const d = Math.sin(t * layer.driftX.freq * speed) * width * layer.driftX.amount;
offsetX += layer.driftX.invert ? -d : d;
}
if (layer.driftY?.enabled) {
const freq = (layer.driftY.freq ?? layer.driftX?.freq ?? 0) * speed;
const d = Math.sin(t * freq) * height * layer.driftY.amount;
offsetY += (layer.driftY.scale ?? 1) * d;
}
// Pure sin/cos position animation — time scaled by speed
if (!layer.driftX?.enabled && layer.animatedX?.enabled) {
offsetX = Math.sin(t * layer.animatedX.freq * speed) * width * layer.animatedX.amount;
}
if (!layer.driftY?.enabled && layer.animatedY?.enabled) {
const fn = layer.animatedY.type === "cos" ? Math.cos : Math.sin;
offsetY = fn(t * layer.animatedY.freq * speed) * height * layer.animatedY.amount;
}
// Pointer parallax
offsetX += (px - width * 0.5) * (layer.parallaxX ?? 0);
offsetY += (py - height * 0.5) * (layer.parallaxY ?? 0);
const cx = width * layer.xBase + offsetX;
const cy = height * layer.yBase + offsetY;
const radius = Math.max(width, height) * layer.radiusScale;
// Build gradient — fade alpha down toward edges
let fadedColor;
const baseRgba = layer.color.match(/rgba?\(([^)]+)\)/);
if (baseRgba && baseRgba[1].split(',').length === 4) {
const p = baseRgba[1].split(',');
const newAlpha = parseFloat(p[3]) * 0.5;
fadedColor = `rgba(${p[0]}, ${p[1]}, ${p[2]}, ${newAlpha.toFixed(2)})`;
} else {
fadedColor = layer.color;
}
const gradient = context.createRadialGradient(cx, cy, 0, cx, cy, radius);
gradient.addColorStop(0, layer.color);
gradient.addColorStop(0.55, fadedColor);
gradient.addColorStop(1, "rgba(0, 0, 0, 0)");
context.fillStyle = gradient;
context.fillRect(0, 0, width, height);
}
context.restore();
}
/* ──────────────────────────────────────────────
Shooting star spawning & update
────────────────────────────────────────────── */
function createShootingStar() {
const c = config.shootingStar;
// Pick random edge to spawn from (top or left preferentially)
const edge = Math.random();
let x, y, angleDeg;
if (edge < 0.65) {
// Start from top edge, sweep right-down
x = random(0, width * 0.8);
y = -20;
angleDeg = random(c.angleMin, c.angleMax);
} else if (edge < 0.9) {
// Start from left edge, sweep down-right
x = -20;
y = random(0, height * 0.6);
angleDeg = random(c.angleMin, c.angleMax + 15); // steeper
} else {
// Start from top-right-ish, sweep left-down (rare)
x = random(width * 0.3, width);
y = -20;
angleDeg = random(180 - c.angleMax, 180 - c.angleMin); // reflect
}
// Determine direction based on spawn side
let finalAngle;
if (edge < 0.9) {
// Top/left → down-right
finalAngle = (angleDeg * Math.PI) / 180;
} else {
// Right-ish → down-left
finalAngle = Math.PI - (angleDeg * Math.PI) / 180;
}
return {
x,
y,
angle: finalAngle,
speed: random(c.speedMin, c.speedMax),
vx: Math.cos(finalAngle) * (edge >= 0.9 ? -1 : 1),
vy: Math.sin(finalAngle),
length: random(c.lengthMin, c.lengthMax),
thickness: random(c.thicknessMin, c.thicknessMax),
hue: random(c.hueMin, c.hueMax),
life: 0,
maxLife: random(c.lifetimeMin, c.lifetimeMax),
fadeIn: Math.min(c.fadeInFrames, 3),
};
}
function updateShootingStars() {
const speed = config.motion.speed / 5; // normalise around default of 5
const c = config.shootingStar;
// Spawn check (skip if disabled or reduced motion)
if (c.enabled && !config.motion.prefersReducedMotion) {
if (Math.random() < c.chancePerFrame && shootingStars.length < 2) {
shootingStars.push(createShootingStar());
}
}
// Update existing stars — speed scales movement, inverse speed scales lifetime
for (let i = shootingStars.length - 1; i >= 0; i--) {
const s = shootingStars[i];
s.x += s.vx * s.speed * speed;
s.y += s.vy * s.speed * speed;
s.life += 1 / speed;
// Remove if expired or way off-screen
if (s.life > s.maxLife || s.y > height + 100 || s.x < -200 || s.x > width + 200) {
shootingStars.splice(i, 1);
}
}
}
/* ──────────────────────────────────────────────
Drawing — stars + glow
────────────────────────────────────────────── */
/* ──────────────────────────────────────────────
Drawing — shooting stars
────────────────────────────────────────────── */
function drawShootingStars() {
if (shootingStars.length === 0) return;
const c = config;
const isLight = c.theme === "system"
? resolveTheme({ theme: c.theme }) === "light"
: c.theme === "light";
context.save();
context.globalCompositeOperation = isLight ? "darken" : "screen";
for (const s of shootingStars) {
const fadeProgress = s.life / s.maxLife;
let alpha;
// Fade in quickly, then gradual fade out
if (s.life < s.fadeIn) {
alpha = (s.life / s.fadeIn) * c.shootingStar.headAlpha;
} else {
alpha = c.shootingStar.headAlpha * (1 - (fadeProgress - 0.1) / 0.9);
}
alpha = Math.max(0, alpha);
if (alpha <= 0) continue;
const tailX = s.x - s.vx * s.length * (s.life < s.fadeIn ? s.life / s.fadeIn : 1);
const tailY = s.y - s.vy * s.length * (s.life < s.fadeIn ? s.life / s.fadeIn : 1);
if (isLight) {
// Light mode: dark shooting star trail against light sky
const trailGrad = context.createLinearGradient(tailX, tailY, s.x, s.y);
const tailAlpha = alpha * 0.5;
trailGrad.addColorStop(0, `rgba(60, 50, 100, ${tailAlpha})`);
trailGrad.addColorStop(0.3, `rgba(80, 70, 120, ${alpha * 0.7})`);
trailGrad.addColorStop(1, `rgba(40, 35, 80, ${alpha})`);
context.strokeStyle = trailGrad;
context.lineWidth = s.thickness * (s.life < s.fadeIn ? s.life / s.fadeIn : 1);
context.lineCap = "round";
context.beginPath();
context.moveTo(tailX, tailY);
context.lineTo(s.x, s.y);
context.stroke();
// Dark head dot (no glow on light bg)
const headGlow = context.createRadialGradient(s.x, s.y, 0, s.x, s.y, s.thickness * 2);
headGlow.addColorStop(0, `rgba(30, 25, 70, ${alpha})`);
headGlow.addColorStop(1, "rgba(0, 0, 0, 0)");
context.fillStyle = headGlow;
context.beginPath();
context.arc(s.x, s.y, s.thickness * 2, 0, Math.PI * 2);
context.fill();
} else {
// Dark mode: bright shooting star
const trailGrad = context.createLinearGradient(tailX, tailY, s.x, s.y);
const tailAlpha = alpha * 0.3;
trailGrad.addColorStop(0, `hsla(${s.hue}, 60%, 90%, ${tailAlpha})`);
trailGrad.addColorStop(0.3, `hsla(${s.hue}, 80%, 92%, ${alpha * 0.7})`);
trailGrad.addColorStop(1, `hsla(${s.hue}, 100%, 98%, ${alpha})`);
context.strokeStyle = trailGrad;
context.lineWidth = s.thickness * (s.life < s.fadeIn ? s.life / s.fadeIn : 1);
context.lineCap = "round";
context.beginPath();
context.moveTo(tailX, tailY);
context.lineTo(s.x, s.y);
context.stroke();
// Bright head glow
const headGlow = context.createRadialGradient(s.x, s.y, 0, s.x, s.y, s.thickness * 3);
headGlow.addColorStop(0, `hsla(${s.hue}, 100%, 98%, ${alpha})`);
headGlow.addColorStop(0.4, `hsla(${s.hue}, 100%, 85%, ${alpha * 0.5})`);
headGlow.addColorStop(1, "hsla(0, 0%, 100%, 0)");
context.fillStyle = headGlow;
context.beginPath();
context.arc(s.x, s.y, s.thickness * 3, 0, Math.PI * 2);
context.fill();
}
}
context.restore();
}
function drawStars() {
const c = config;
const isLight = c.theme === "system"
? resolveTheme({ theme: c.theme }) === "light"
: c.theme === "light";
context.save();
context.globalCompositeOperation = isLight ? "darken" : "lighter";
for (const star of stars) {
const radius = star.radius * (0.7 + star.depth * 0.9) * star.twinkle;
const alpha = c.visual.alphaBase + star.depth * c.visual.alphaDepthScale;
const hue = star.hue;
if (isLight) {
// Light mode: draw dark stars (like daytime sky view)
context.fillStyle = `hsla(${hue}, 50%, 28%, ${alpha})`;
} else {
// Dark mode: bright white/blue stars
context.fillStyle = `hsla(${hue}, 100%, 88%, ${alpha})`;
}
context.beginPath();
context.arc(star.screenX, star.screenY, radius, 0, Math.PI * 2);
context.fill();
if (star.depth > c.visual.glowThreshold) {
const glowRadius = radius * c.visual.glowRadiusMultiplier;
const glow = context.createRadialGradient(star.screenX, star.screenY, 0, star.screenX, star.screenY, glowRadius);
if (isLight) {
// No glow in light mode — stars are dark dots
glow.addColorStop(0, `rgba(0, 0, 0, ${alpha * c.visual.glowAlphaMultiplier})`);
} else {
glow.addColorStop(0, `hsla(${hue}, 100%, 85%, ${alpha * c.visual.glowAlphaMultiplier})`);
}
glow.addColorStop(1, "rgba(0, 0, 0, 0)");
context.fillStyle = glow;
context.beginPath();
context.arc(star.screenX, star.screenY, glowRadius, 0, Math.PI * 2);
context.fill();
}
}
context.restore();
}
/* ──────────────────────────────────────────────
Update — parallax, drift, twinkle
────────────────────────────────────────────── */
function updateStars(time) {
const speed = config.motion.speed / 5; // normalise around default of 5
const c = config;
const pointerX = pointer.x - 0.5;
const pointerY = pointer.y - 0.5;
for (const star of stars) {
if (!c.motion.prefersReducedMotion) {
const driftScale = c.starMotion.driftBase + star.depth * c.starMotion.driftDepthScale;
star.x = (star.x + star.speedX * driftScale * speed + pointerX * c.parallax.sensitivityX * (1 - star.depth) * speed + 1) % 1;
star.y = (star.y + star.speedY * driftScale * speed + pointerY * c.parallax.sensitivityY * (1 - star.depth) * speed + 1) % 1;
}
star.screenX = star.x * width + pointerX * width * c.parallax.depthFactorX * (1 - star.depth);
star.screenY = star.y * height + pointerY * height * c.parallax.depthFactorY * (1 - star.depth);
star.twinkle = 1 + Math.sin(time * star.twinkleSpeed + star.phase) * c.visual.twinkleAmplitude;
}
}
/* ──────────────────────────────────────────────
Render loop
────────────────────────────────────────────── */
function render(timestamp) {
const c = config.motion;
if (lastFrameTime && timestamp - lastFrameTime < c.frameMs) {
animationId = requestAnimationFrame(render);
return;
}
lastFrameTime = timestamp;
const time = timestamp * 0.001;
pointer.x = lerp(pointer.x, pointer.targetX, c.pointerLerp);
pointer.y = lerp(pointer.y, pointer.targetY, c.pointerLerp);
context.clearRect(0, 0, width, height);
drawBackdrop(time);
updateStars(time);
updateShootingStars();
drawShootingStars();
drawStars();
if (c.prefersReducedMotion) return; // still render but don't loop
animationId = requestAnimationFrame(render);
}
/* ──────────────────────────────────────────────
Event wiring
────────────────────────────────────────────── */
function bindEvents() {
window.addEventListener("resize", resize, { passive: true });
window.addEventListener(
"pointermove",
(event) => {
pointer.targetX = clamp(event.clientX / Math.max(width, 1), 0, 1);
pointer.targetY = clamp(event.clientY / Math.max(height, 1), 0, 1);
},
{ passive: true },
);
window.addEventListener(
"pointerleave",
() => {
pointer.targetX = 0.5;
pointer.targetY = 0.5;
},
{ passive: true },
);
window.addEventListener("visibilitychange", () => {
if (!document.hidden) {
lastFrameTime = 0;
startRender();
}
});
}
function startRender() {
stopRender();
animationId = requestAnimationFrame(render);
}
function stopRender() {
if (animationId !== null) {
cancelAnimationFrame(animationId);
animationId = null;
}
}
/* ──────────────────────────────────────────────
Public API
────────────────────────────────────────────── */
/**
* Initialise the constellation background on a canvas element.
* @param {HTMLCanvasElement} el — the <canvas> to render into (or an id string)
* @param {object} [userConfig] — runtime configuration overrides
*/
function init(el, userConfig) {
if (initialized) return; // already running
canvas = typeof el === "string" ? document.querySelector(el) : el;
if (!canvas) throw new Error(`Constell: canvas "${el}" not found`);
context = canvas.getContext("2d", { alpha: true, desynchronized: true });
config = userConfig ? mergeConfig(userConfig) : structuredClone(DEFAULT_CONFIG);
resize();
seedStars();
bindEvents();
startRender();
initialized = true;
}
/**
* Apply configuration overrides at runtime.
* Stars are re-seeded when star.count changes.
* @param {object} overrides — partial config to merge over the current one
*/
function configure(overrides) {
if (!initialized) throw new Error("Constell: call init() before configure()");
const countBefore = config.star.count;
config = mergeConfig(overrides);
// Re-seed if star count changed
if (config.star.count !== countBefore) {
seedStars();
}
}
/**
* Toggle or set the active theme.
* @param {"dark"|"light"} [mode] — explicit mode, or toggle on repeated calls without arg
* @returns {"dark"|"light"} the resolved theme name that was set
*/
function toggleTheme(mode) {
if (!initialized) throw new Error("Constell: call init() before toggleTheme()");
// If no mode given, toggle: dark ↔ light
if (mode === undefined) {
mode = config.theme === "dark" ? "light" : "dark";
}
config.theme = mode;
document.body.setAttribute("data-theme", mode === "system" ? (resolveTheme(config) === "light" ? "light" : "dark") : mode);
// Apply ONLY the theme-specific overrides into the existing config.
// This preserves non-theme settings (motion.frameMs, parallax, etc.)
const resolved = resolveTheme({ theme: mode });
const th = THEMES[resolved];
if (!th) return mode;
for (const key of ["star", "motion", "parallax", "visual"]) {
if (key in th && typeof th[key] === "object") {
Object.assign(config[key], th[key]);
}
}
if (Array.isArray(th.nebula)) {
for (let i = 0; i < th.nebula.length && i < config.nebula.length; i++) {
if (typeof th.nebula[i] === "object") {
Object.assign(config.nebula[i], th.nebula[i]);
}
}
}
if (th.shootingStar && typeof th.shootingStar === "object") {
Object.assign(config.shootingStar, th.shootingStar);
}
if (th.backdrop && typeof th.backdrop === "object") {
Object.assign(config.backdrop, th.backdrop);
}
// Stars need re-generation with new hue ranges for theme colors
seedStars();
return mode;
}
/* ──────────────────────────────────────────────
Exports
────────────────────────────────────────────── */
const Constell = { init, configure, toggleTheme };
export { Constell };
// Also support non-module usage via a global when imported as <script>
if (typeof window !== "undefined") {
window.Constell = Constell;
}