@arraypress/effects-astro 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -20,9 +20,10 @@ export { flutedGlass } from './runtime/fluted-glass.js';
20
20
  export { particleLogo } from './runtime/particle-logo.js';
21
21
  export { pointCloud } from './runtime/point-cloud.js';
22
22
  export { voxelLogo } from './runtime/voxel-logo.js';
23
- export { pixelGlitch, outlineAlpha } from './runtime/pixel-glitch.js';
23
+ export { pixelGlitch, outlineAlpha, rowTears } from './runtime/pixel-glitch.js';
24
+ export { pixelFountain, createFountain, fadeSteps, shadeAt, tierSizes, pixelRect, inkedCells, MAX_PIXELS } from './runtime/pixel-fountain.js';
24
25
  export { fit, fitText } from './runtime/fit-text.js';
25
- export { textNodes, textRange, splitLetters, joinLetters } from './runtime/text.js';
26
+ export { textNodes, textRange, splitLetters, joinLetters, textNodesWithin, paintGlyphs } from './runtime/text.js';
26
27
  export { variableType, DEFAULT_AXES } from './runtime/variable-type.js';
27
28
  export { dotGrid } from './runtime/dot-grid.js';
28
29
  export { signalLines, waveBars } from './runtime/waves.js';
@@ -51,7 +52,7 @@ export { haloRing } from './runtime/halo-ring.js';
51
52
  export { silkRibbon } from './runtime/silk-ribbon.js';
52
53
  export { radiantGlass } from './runtime/radiant-glass.js';
53
54
  export { topography } from './runtime/topography.js';
54
- export { galaxy, galaxyRamp, nebulaField } from './runtime/galaxy.js';
55
+ export { galaxy, galaxyRamp, galaxyStops, nebulaField } from './runtime/galaxy.js';
55
56
  export { caustics, causticTones } from './runtime/caustics.js';
56
57
  export { rainOnGlass } from './runtime/rain-on-glass.js';
57
58
  export { ocean } from './runtime/ocean.js';
@@ -62,7 +63,7 @@ export { slideshow } from './runtime/slideshow.js';
62
63
  export { productStack } from './runtime/product-stack.js';
63
64
  export { imageRipple, fitScale } from './runtime/image-ripple.js';
64
65
  export { stackPoses, stackBounds, poseTransform, poseFilter, LAYOUTS as STACK_LAYOUTS } from './runtime/stack-poses.js';
65
- export { createCanvas2D, grainPattern, grainOnto } from './runtime/canvas2d.js';
66
+ export { createCanvas2D, claimCanvas, grainPattern, grainOnto } from './runtime/canvas2d.js';
66
67
  export { loadImage, imageTexture, coverScale, GLSL_COVER } from './runtime/image.js';
67
68
  export { boxBlur } from './runtime/blur.js';
68
69
  export { paperShader, paperSettings, paperUniforms } from './runtime/paper.js';
@@ -75,7 +76,7 @@ export { createStage } from './runtime/stage.js';
75
76
  export { createMesh, STRIDE } from './runtime/mesh.js';
76
77
  export { isoCamera, ISO_PITCH } from './runtime/iso-camera.js';
77
78
  export { instancing } from './runtime/instancing.js';
78
- export { seededRandom } from './runtime/random.js';
79
+ export { seededRandom, parkMiller, randomFrom, RANDOMS } from './runtime/random.js';
79
80
  export { createPingPong, floatFormats } from './runtime/ping-pong.js';
80
81
  export { createHeightField, GLSL_HEIGHT_FIELD, MAX_PUSHES } from './runtime/height-field.js';
81
82
  export { createPoints, projectPoint, GLSL_PROJECT } from './runtime/points.js';
@@ -6,11 +6,20 @@ export interface Canvas2D {
6
6
  /** The element's size, CSS px. */
7
7
  width: number;
8
8
  height: number;
9
+ /** The canvas's pixels per CSS px (the device's, up to 2). */
10
+ dpr: number;
9
11
  /** True with prefers-reduced-motion. */
10
12
  still: boolean;
11
13
  }
12
14
 
13
- /** Starts a Canvas 2D effect in `el`'s canvas: sized, looped while near the screen, still with reduced motion. */
15
+ /**
16
+ * The element's canvas, ready for 2D drawing: its first canvas, or a fresh one in its place (with its attributes)
17
+ * when that one is already claimed for WebGL, or a fresh one added when it has none. `release` puts the element's
18
+ * own canvas back (or takes the added one out).
19
+ */
20
+ export function claimCanvas(el: HTMLElement): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D | null; release(): void };
21
+
22
+ /** Starts a Canvas 2D effect in `el`'s canvas (or one in its place: see claimCanvas): sized, looped while near the screen, still with reduced motion. */
14
23
  export function createCanvas2D(
15
24
  el: HTMLElement,
16
25
  options: { draw(c: Canvas2D, now: number, dt: number): void; resize?(c: Canvas2D): void },
@@ -6,6 +6,12 @@
6
6
  * frames from the page's one loop while it is near the screen, one still
7
7
  * frame with prefers-reduced-motion (redrawn on resize), and a grain tile
8
8
  * for texturing strokes.
9
+ *
10
+ * A canvas holds one kind of context for life, so when the element's
11
+ * canvas has already been claimed for WebGL (a host that makes one canvas
12
+ * for whichever effect it shows), a fresh canvas takes its place, with
13
+ * its attributes, and the host's goes back when the effect stops. An
14
+ * element with no canvas gets one.
9
15
  */
10
16
 
11
17
  import { prefersReducedMotion } from './device.js';
@@ -17,11 +23,37 @@ import { animate } from './loop.js';
17
23
  * @property {HTMLCanvasElement} canvas The canvas.
18
24
  * @property {number} width The element's width, CSS px.
19
25
  * @property {number} height The element's height, CSS px.
26
+ * @property {number} dpr The canvas's pixels per CSS px (the device's, up to 2).
20
27
  * @property {boolean} still True with prefers-reduced-motion.
21
28
  */
22
29
 
23
30
  /**
24
- * Starts a Canvas 2D effect on an element (its first canvas is drawn into).
31
+ * The element's canvas, ready for 2D drawing: its first canvas, or a
32
+ * fresh one in its place when that one is already claimed for another
33
+ * kind of context (WebGL), or a fresh one added when it has none.
34
+ *
35
+ * @param {HTMLElement} el The element.
36
+ * @returns {{ canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D | null, release: () => void }} The canvas, its context and a function that puts the element's own canvas back.
37
+ */
38
+ export function claimCanvas(el) {
39
+ const found = el.querySelector('canvas');
40
+ const ctx = found?.getContext('2d', { alpha: true });
41
+ if (found && ctx) return { canvas: found, ctx, release: () => {} };
42
+ const canvas = document.createElement('canvas');
43
+ if (found) {
44
+ for (const { name, value } of found.attributes) canvas.setAttribute(name, value);
45
+ found.replaceWith(canvas);
46
+ } else el.append(canvas);
47
+ return {
48
+ canvas,
49
+ ctx: canvas.getContext('2d', { alpha: true }),
50
+ release: () => (found ? canvas.replaceWith(found) : canvas.remove()),
51
+ };
52
+ }
53
+
54
+ /**
55
+ * Starts a Canvas 2D effect on an element (its first canvas is drawn into,
56
+ * or one in its place: see claimCanvas).
25
57
  *
26
58
  * @param {HTMLElement} el The element.
27
59
  * @param {object} options The effect.
@@ -30,20 +62,22 @@ import { animate } from './loop.js';
30
62
  * @returns {{ c: Canvas2D | null, stop: () => void }} The canvas (null without a 2D context) and a function that stops it.
31
63
  */
32
64
  export function createCanvas2D(el, options) {
33
- const canvas = el.querySelector('canvas');
34
- const ctx = canvas?.getContext('2d', { alpha: true });
35
- if (!canvas || !ctx) return { c: null, stop: () => {} };
65
+ const { canvas, ctx, release } = claimCanvas(el);
66
+ if (!ctx) {
67
+ release();
68
+ return { c: null, stop: () => {} };
69
+ }
36
70
  /** @type {Canvas2D} */
37
- const c = { ctx, canvas, width: 0, height: 0, still: prefersReducedMotion() };
71
+ const c = { ctx, canvas, width: 0, height: 0, dpr: 1, still: prefersReducedMotion() };
38
72
 
39
73
  /** Sizes the canvas to the element. */
40
74
  const size = () => {
41
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
75
+ c.dpr = Math.min(window.devicePixelRatio || 1, 2);
42
76
  c.width = Math.max(1, el.clientWidth);
43
77
  c.height = Math.max(1, el.clientHeight);
44
- canvas.width = Math.floor(c.width * dpr);
45
- canvas.height = Math.floor(c.height * dpr);
46
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
78
+ canvas.width = Math.floor(c.width * c.dpr);
79
+ canvas.height = Math.floor(c.height * c.dpr);
80
+ ctx.setTransform(c.dpr, 0, 0, c.dpr, 0, 0);
47
81
  options.resize?.(c);
48
82
  if (c.still) options.draw(c, performance.now(), 0);
49
83
  };
@@ -56,6 +90,7 @@ export function createCanvas2D(el, options) {
56
90
  stop: () => {
57
91
  stopLoop();
58
92
  resizer.disconnect();
93
+ release();
59
94
  },
60
95
  };
61
96
  }
@@ -1,4 +1,5 @@
1
1
  import type { PaletteName } from './palettes.js';
2
+ import type { RandomName } from './random.js';
2
3
 
3
4
  export interface GalaxyConfig {
4
5
  /** The nebula's colours, deep to bright (two to five read best), blended in Oklab from near-black up to a pale highlight. Default indigo, cornflower, violet and cyan. */
@@ -13,6 +14,17 @@ export interface GalaxyConfig {
13
14
  glitter?: number;
14
15
  /** Which sky, 1–999: the same seed draws the same nebula and stars. Default 7. */
15
16
  seed?: number;
17
+ /** The glitter and stars' own seed. Default `seed × 31 + 1`. */
18
+ starSeed?: number;
19
+ /**
20
+ * The generator. `mulberry32` scatters the glitter and stars afresh from `starSeed` on each resize;
21
+ * `park-miller` (the Logomarks studio's first galaxy) scatters them from one stream that runs on across
22
+ * resizes. With `seed: 7`, `starSeed: 31` and `blend: 'srgb'`, `park-miller` draws that sky to the pixel.
23
+ * Default `mulberry32`.
24
+ */
25
+ rng?: RandomName;
26
+ /** How the ramp blends its colours: in Oklab, or plainly in sRGB (painted exactly along its stops, the first colour's bytes × 0.18 for its near-black). Default `oklab`. */
27
+ blend?: 'oklab' | 'srgb';
16
28
  /** Run only while near the screen (true, or a CSS length; default `200px`), handled by `mount`. Default false. */
17
29
  lazy?: boolean | string;
18
30
  }
@@ -24,14 +36,17 @@ export const COLORS: string[];
24
36
  export const NEBULA_WIDTH: number;
25
37
  export const NEBULA_HEIGHT: number;
26
38
 
27
- /** The nebula as places on the colour ramp, 0–1, one a pixel row by row: layered noise clouds cut by ridged dust lanes. Tileable; the same seed gives the same field. */
28
- export function nebulaField(width: number, height: number, seed?: number): Float32Array;
39
+ /** The nebula as places on the colour ramp, 0–1, one a pixel row by row: layered noise clouds cut by ridged dust lanes. Tileable; the same seed and generator (default `mulberry32`) give the same field. */
40
+ export function nebulaField(width: number, height: number, seed?: number, rng?: RandomName): Float64Array;
29
41
 
30
- /** The ramp the nebula is painted along (the first colour darkened to near-black, the colours, a pale top), blended in Oklab: `steps` (default 256) RGB triples. Throws a TypeError for a colour that is not hex. */
31
- export function galaxyRamp(colors: string[], steps?: number): Uint8ClampedArray;
42
+ /** The ramp's stops (the first colour darkened to near-black, the colours, the pale top) as RGB triples, 0–255, unrounded. Darkened in Oklab, or for `srgb` by scaling its bytes by 0.18. Throws a TypeError for a colour that is not hex. */
43
+ export function galaxyStops(colors: string[], blend?: 'oklab' | 'srgb'): Float64Array;
32
44
 
33
- /** Paints a nebula field along a ramp: opaque RGBA, a pixel per value. */
34
- export function nebulaPixels(field: Float32Array, ramp: Uint8ClampedArray): Uint8ClampedArray;
45
+ /** The ramp the nebula is painted along (the first colour darkened to near-black, the colours, a pale top), blended in Oklab (default) or sRGB: `steps` (default 256) RGB triples. Throws a TypeError for a colour that is not hex. */
46
+ export function galaxyRamp(colors: string[], steps?: number, blend?: 'oklab' | 'srgb'): Uint8ClampedArray;
35
47
 
36
- /** Starts the galaxy on an element (its first canvas is drawn into). Returns a function that stops it. */
48
+ /** Paints a nebula field along a ramp: opaque RGBA, a pixel per value. Each value takes the nearest entry, or with `smooth` the linear blend of the two either side (for galaxyStops with `srgb`, which it paints exactly). */
49
+ export function nebulaPixels(field: ArrayLike<number>, ramp: ArrayLike<number>, smooth?: boolean): Uint8ClampedArray;
50
+
51
+ /** Starts the galaxy on an element (its first canvas is drawn into, or a 2D one in its place when the host made it for WebGL). Returns a function that stops it. */
37
52
  export function galaxy(el: HTMLElement, config: GalaxyConfig): () => void;
@@ -10,21 +10,29 @@
10
10
  * noise: five octaves for the clouds, three ridged ones for the dust, and a
11
11
  * broad field that shifts the colours along the ramp so they wander. Each
12
12
  * frame draws it scaled up to cover (it is soft anyway) at a slowly
13
- * drifting offset, the glitter over it at full resolution, then the stars
14
- * from one pre-drawn sprite per tint. The ramp runs from near-black
15
- * through the palette to a pale highlight, blended in Oklab; new colours
16
- * (`setColors`) only remap the worked-out field.
13
+ * drifting offset, then the glitter and the stars over it, all in device
14
+ * pixels. The ramp runs from near-black through the palette to a pale
15
+ * highlight, blended in Oklab (or plainly in sRGB, `blend: 'srgb'`); new
16
+ * colours (`setColors`) only remap the worked-out field.
17
17
  *
18
- * Canvas 2D, opaque. One still frame with prefers-reduced-motion.
18
+ * The sky comes from `seed` (the nebula) and `starSeed` (the glitter and
19
+ * stars), by mulberry32, scattered afresh from `starSeed` on each resize.
20
+ * `rng: 'park-miller'` uses the Park–Miller generator instead, as the
21
+ * Logomarks studio's first galaxy did, with its glitter and stars from one
22
+ * stream that runs on across resizes; with `seed: 7`, `starSeed: 31` and
23
+ * `blend: 'srgb'` that is its sky to the pixel.
24
+ *
25
+ * Canvas 2D, opaque. One still frame with prefers-reduced-motion. A host
26
+ * canvas already claimed for WebGL is swapped for a 2D one (canvas2d.js).
19
27
  *
20
28
  * From the Logomarks studio's showcase.
21
29
  */
22
30
 
23
31
  import { createCanvas2D } from './canvas2d.js';
24
- import { mixOklab, parseColor } from './color.js';
32
+ import { mixOklab, parseColor, toHex } from './color.js';
25
33
  import { watchColors } from './mount.js';
26
34
  import { pickColors } from './palettes.js';
27
- import { seededRandom } from './random.js';
35
+ import { randomFrom } from './random.js';
28
36
 
29
37
  /**
30
38
  * @typedef {object} GalaxyConfig
@@ -34,6 +42,9 @@ import { seededRandom } from './random.js';
34
42
  * @property {number} [stars=1] How many stars, as a share of the usual.
35
43
  * @property {number} [glitter=1] How bright the glitter is, as a share of the usual.
36
44
  * @property {number} [seed=7] Which sky: the same seed draws the same nebula and stars.
45
+ * @property {number} [starSeed] The glitter and stars' own seed. Default `seed × 31 + 1`.
46
+ * @property {import('./random.js').RandomName} [rng='mulberry32'] The generator: `park-miller` for the studio's first sky (its scatter runs on across resizes).
47
+ * @property {'oklab' | 'srgb'} [blend='oklab'] How the ramp blends its colours: in Oklab, or plainly in sRGB (and painted exactly along its stops).
37
48
  */
38
49
 
39
50
  /** The colours without `colors` or `palette`: indigo, cornflower, violet and cyan. */
@@ -43,8 +54,17 @@ export const COLORS = ['#3a2bd9', '#5c7cff', '#b45cff', '#5cecff'];
43
54
  export const NEBULA_WIDTH = 400;
44
55
  export const NEBULA_HEIGHT = 225;
45
56
 
46
- /** The ramp's top: a pale, faintly violet white. */
47
- const PALE = /** @type {import('./color.js').Rgb} */ ([245 / 255, 240 / 255, 1]);
57
+ /** The ramp's top: a pale, faintly violet white, as bytes. */
58
+ const PALE_BYTES = [245, 240, 255];
59
+
60
+ /** The ramp's top, 0–1. */
61
+ const PALE = /** @type {import('./color.js').Rgb} */ (PALE_BYTES.map((v) => v / 255));
62
+
63
+ /** The near-black the ramp starts from: the first colour mixed this far to black in Oklab… */
64
+ const DEEP_OKLAB = 0.62;
65
+
66
+ /** …or, blended in sRGB, its bytes scaled by this. */
67
+ const DEEP_SRGB = 0.18;
48
68
 
49
69
  /** Star tints besides the palette's own: white, a violet white and a blue white. */
50
70
  const WHITES = ['#ffffff', '#f2e9ff', '#e6f6ff'];
@@ -90,14 +110,15 @@ function lattice(n, rnd) {
90
110
  * @param {number} width Across, px.
91
111
  * @param {number} height Down, px.
92
112
  * @param {number} [seed=7] The same seed gives the same nebula.
93
- * @returns {Float32Array} One value a pixel, 0 (dark) to 1 (the pale top), row by row.
113
+ * @param {import('./random.js').RandomName} [rng='mulberry32'] The generator.
114
+ * @returns {Float64Array} One value a pixel, 0 (dark) to 1 (the pale top), row by row.
94
115
  */
95
- export function nebulaField(width, height, seed = 7) {
96
- const rnd = seededRandom(seed);
116
+ export function nebulaField(width, height, seed = 7, rng = 'mulberry32') {
117
+ const rnd = randomFrom(rng, seed);
97
118
  const octaves = [3, 6, 12, 24, 48].map((n) => lattice(n, rnd));
98
119
  const dust = [5, 10, 20].map((n) => lattice(n, rnd));
99
120
  const hue = lattice(2, rnd);
100
- const out = new Float32Array(width * height);
121
+ const out = new Float64Array(width * height);
101
122
  for (let y = 0; y < height; y++) {
102
123
  for (let x = 0; x < width; x++) {
103
124
  const u = x / width;
@@ -121,20 +142,54 @@ export function nebulaField(width, height, seed = 7) {
121
142
  return out;
122
143
  }
123
144
 
145
+ /**
146
+ * The colours as channels, the default four when there are none.
147
+ *
148
+ * @param {string[]} colors The colours, as CSS hex.
149
+ * @returns {import('./color.js').Rgb[]} Their channels, 0–1.
150
+ * @throws {TypeError} When a colour is not hex.
151
+ */
152
+ function parsed(colors) {
153
+ return (colors.length ? colors : COLORS).map(parseColor);
154
+ }
155
+
156
+ /**
157
+ * The ramp's stops: near-black (the first colour darkened), the colours
158
+ * in order, then the pale top. Darkened in Oklab, or, for `srgb`, by
159
+ * scaling the colour's bytes (unrounded, as the studio's first ramp did).
160
+ *
161
+ * @param {string[]} colors The colours, as CSS hex; the default four when empty.
162
+ * @param {'oklab' | 'srgb'} [blend='oklab'] How the ramp blends.
163
+ * @returns {Float64Array} One RGB triple a stop, 0–255, unrounded.
164
+ * @throws {TypeError} When a colour is not hex.
165
+ */
166
+ export function galaxyStops(colors, blend = 'oklab') {
167
+ const cs = parsed(colors);
168
+ const bytes = cs.map((c) => c.map((v) => Math.round(v * 255)));
169
+ const deep = blend === 'srgb' ? bytes[0].map((v) => v * DEEP_SRGB) : mixOklab(cs[0], [0, 0, 0], DEEP_OKLAB).map((v) => v * 255);
170
+ return Float64Array.from([deep, ...bytes, PALE_BYTES].flat());
171
+ }
172
+
124
173
  /**
125
174
  * The colour ramp the nebula is painted along: near-black (the first
126
175
  * colour, darkened), the colours in order, then a pale highlight, each
127
- * stretch blended in Oklab.
176
+ * stretch blended in Oklab (or plainly in sRGB).
128
177
  *
129
178
  * @param {string[]} colors The colours, as CSS hex.
130
179
  * @param {number} [steps=256] How many entries.
180
+ * @param {'oklab' | 'srgb'} [blend='oklab'] How the stretches blend.
131
181
  * @returns {Uint8ClampedArray} `steps` RGB triples, 0–255.
132
182
  * @throws {TypeError} When a colour is not hex.
133
183
  */
134
- export function galaxyRamp(colors, steps = 256) {
135
- const cs = (colors.length ? colors : COLORS).map(parseColor);
136
- const stops = [mixOklab(cs[0], [0, 0, 0], 0.62), ...cs, PALE];
184
+ export function galaxyRamp(colors, steps = 256, blend = 'oklab') {
137
185
  const out = new Uint8ClampedArray(steps * 3);
186
+ if (blend === 'srgb') {
187
+ const stops = galaxyStops(colors, 'srgb');
188
+ for (let s = 0; s < steps; s++) along(stops, s / (steps - 1), out, s * 3);
189
+ return out;
190
+ }
191
+ const cs = parsed(colors);
192
+ const stops = [mixOklab(cs[0], [0, 0, 0], DEEP_OKLAB), ...cs, PALE];
138
193
  for (let s = 0; s < steps; s++) {
139
194
  const k = (s / (steps - 1)) * (stops.length - 1);
140
195
  const i = Math.min(stops.length - 2, Math.floor(k));
@@ -145,48 +200,74 @@ export function galaxyRamp(colors, steps = 256) {
145
200
  }
146
201
 
147
202
  /**
148
- * Paints a nebula field along a ramp.
203
+ * Writes the colour a place along some stops comes to, blended linearly
204
+ * between the two either side of it.
149
205
  *
150
- * @param {Float32Array} field From nebulaField.
151
- * @param {Uint8ClampedArray} ramp From galaxyRamp.
206
+ * @param {ArrayLike<number>} stops RGB triples.
207
+ * @param {number} t Where along them, 0–1.
208
+ * @param {Uint8ClampedArray} out Where to write it (rounded as it is stored).
209
+ * @param {number} at The index of its red.
210
+ */
211
+ function along(stops, t, out, at) {
212
+ const n = stops.length / 3;
213
+ const k = t * (n - 1);
214
+ const i = Math.min(n - 2, Math.floor(k));
215
+ const f = k - i;
216
+ for (let ch = 0; ch < 3; ch++) {
217
+ const a = stops[i * 3 + ch];
218
+ out[at + ch] = a + (stops[(i + 1) * 3 + ch] - a) * f;
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Paints a nebula field along a ramp: each value takes the nearest entry,
224
+ * or, `smooth`, the blend of the two either side of it (for a ramp given
225
+ * only at its stops, such as galaxyStops with `srgb`, which paints it
226
+ * exactly).
227
+ *
228
+ * @param {ArrayLike<number>} field From nebulaField.
229
+ * @param {ArrayLike<number>} ramp From galaxyRamp (or galaxyStops, `smooth`).
230
+ * @param {boolean} [smooth=false] Blend between entries rather than take the nearest.
152
231
  * @returns {Uint8ClampedArray} RGBA, opaque, one pixel per value of the field.
153
232
  */
154
- export function nebulaPixels(field, ramp) {
233
+ export function nebulaPixels(field, ramp, smooth = false) {
155
234
  const last = ramp.length / 3 - 1;
156
235
  const out = new Uint8ClampedArray(field.length * 4);
157
236
  for (let p = 0; p < field.length; p++) {
158
- const i = Math.round(field[p] * last) * 3;
159
- out[p * 4] = ramp[i];
160
- out[p * 4 + 1] = ramp[i + 1];
161
- out[p * 4 + 2] = ramp[i + 2];
237
+ if (smooth) along(ramp, field[p], out, p * 4);
238
+ else {
239
+ const i = Math.round(field[p] * last) * 3;
240
+ out[p * 4] = ramp[i];
241
+ out[p * 4 + 1] = ramp[i + 1];
242
+ out[p * 4 + 2] = ramp[i + 2];
243
+ }
162
244
  out[p * 4 + 3] = 255;
163
245
  }
164
246
  return out;
165
247
  }
166
248
 
167
249
  /**
168
- * A star's glow, drawn once: a radial gradient in the tint, solid at the
169
- * centre and gone at the edge.
250
+ * Paints a star's glow: a radial gradient in the tint, solid at the
251
+ * centre, two thirds at a quarter of the way out, gone at the edge.
170
252
  *
171
- * @param {string} tint CSS hex.
172
- * @returns {HTMLCanvasElement} 64 × 64.
253
+ * @param {CanvasRenderingContext2D} ctx The context, in device px.
254
+ * @param {number} x Its centre across.
255
+ * @param {number} y Its centre down.
256
+ * @param {number} radius The glow's radius.
257
+ * @param {string} tint `#rrggbb`.
173
258
  */
174
- function starSprite(tint) {
175
- const [r, g, b] = parseColor(tint).map((v) => Math.round(v * 255));
176
- const sprite = document.createElement('canvas');
177
- sprite.width = sprite.height = 64;
178
- const s = /** @type {CanvasRenderingContext2D} */ (sprite.getContext('2d'));
179
- const glow = s.createRadialGradient(32, 32, 0, 32, 32, 32);
180
- glow.addColorStop(0, `rgb(${r} ${g} ${b})`);
181
- glow.addColorStop(0.25, `rgb(${r} ${g} ${b} / 0.67)`);
182
- glow.addColorStop(1, `rgb(${r} ${g} ${b} / 0)`);
183
- s.fillStyle = glow;
184
- s.fillRect(0, 0, 64, 64);
185
- return sprite;
259
+ function starGlow(ctx, x, y, radius, tint) {
260
+ const glow = ctx.createRadialGradient(x, y, 0, x, y, radius);
261
+ glow.addColorStop(0, tint);
262
+ glow.addColorStop(0.25, `${tint}aa`);
263
+ glow.addColorStop(1, `${tint}00`);
264
+ ctx.fillStyle = glow;
265
+ ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
186
266
  }
187
267
 
188
268
  /**
189
- * Starts the galaxy on an element (its first canvas is drawn into).
269
+ * Starts the galaxy on an element (its first canvas is drawn into, or a
270
+ * 2D one in its place when the host made it for WebGL).
190
271
  *
191
272
  * @param {HTMLElement} el The element.
192
273
  * @param {GalaxyConfig} config The settings.
@@ -197,74 +278,90 @@ export function galaxy(el, config) {
197
278
  const STARS = Math.max(0, config.stars ?? 1);
198
279
  const GLITTER = Math.max(0, config.glitter ?? 1);
199
280
  const SEED = config.seed ?? 7;
281
+ const STAR_SEED = config.starSeed ?? SEED * 31 + 1;
282
+ const RNG = config.rng ?? 'mulberry32';
283
+ const BLEND = config.blend === 'srgb' ? 'srgb' : 'oklab';
200
284
  let colors = pickColors(config, COLORS);
201
285
 
202
- const field = nebulaField(NEBULA_WIDTH, NEBULA_HEIGHT, SEED);
286
+ const field = nebulaField(NEBULA_WIDTH, NEBULA_HEIGHT, SEED, RNG);
203
287
  const nebula = document.createElement('canvas');
204
288
  nebula.width = NEBULA_WIDTH;
205
289
  nebula.height = NEBULA_HEIGHT;
206
290
  const nctx = nebula.getContext('2d');
207
- /** @type {HTMLCanvasElement[]} */
208
- let sprites = [];
291
+ /** @type {string[]} */
292
+ let tints = [];
209
293
 
210
- /** Paints the nebula and the star sprites in the current colours. */
294
+ /** Paints the nebula and picks the star tints in the current colours. */
211
295
  const paint = () => {
212
- nctx?.putImageData(new ImageData(nebulaPixels(field, galaxyRamp(colors)), NEBULA_WIDTH, NEBULA_HEIGHT), 0, 0);
213
- sprites = [...WHITES, ...colors].map(starSprite);
296
+ const pixels = BLEND === 'srgb' ? nebulaPixels(field, galaxyStops(colors, 'srgb'), true) : nebulaPixels(field, galaxyRamp(colors));
297
+ nctx?.putImageData(new ImageData(pixels, NEBULA_WIDTH, NEBULA_HEIGHT), 0, 0);
298
+ tints = [...WHITES, ...colors].map((c) => toHex(parseColor(c)));
214
299
  };
215
300
  paint();
216
301
 
217
302
  /** @type {HTMLCanvasElement | null} */
218
303
  let glitter = null;
304
+ /** Each star in device px; `tint` is a 0–1 pick from the tints, so new colours keep it. */
219
305
  /** @type {{ x: number, y: number, r: number, phase: number, rate: number, cross: boolean, tint: number }[]} */
220
306
  let stars = [];
221
- let dpr = 1;
307
+ // Park–Miller's scatter is one stream that runs on across resizes; mulberry32's starts afresh each time.
308
+ const running = RNG === 'park-miller' ? randomFrom(RNG, STAR_SEED) : null;
222
309
  const start = performance.now();
223
310
 
224
311
  /**
225
- * Scatters the glitter and stars over the new size, the same way for
226
- * the same seed and size.
312
+ * Scatters the glitter and stars over the new size, in device px.
227
313
  *
228
314
  * @param {import('./canvas2d.js').Canvas2D} c The canvas.
229
315
  */
230
316
  const resize = (c) => {
231
- dpr = c.canvas.width / c.width;
232
- const rnd = seededRandom(SEED * 31 + 1);
317
+ // Nothing to scatter over while the element has no size (and no numbers spent).
318
+ if (!el.clientWidth || !el.clientHeight) {
319
+ glitter = null;
320
+ stars = [];
321
+ return;
322
+ }
323
+ const { dpr } = c;
324
+ const w = c.canvas.width;
325
+ const h = c.canvas.height;
326
+ const rnd = running ?? randomFrom(RNG, STAR_SEED);
233
327
  // Glitter: fine bright speckle at device resolution.
234
328
  glitter = document.createElement('canvas');
235
- glitter.width = c.canvas.width;
236
- glitter.height = c.canvas.height;
329
+ glitter.width = w;
330
+ glitter.height = h;
237
331
  const g = glitter.getContext('2d');
238
332
  if (g) {
239
- for (let k = 0; k < (glitter.width * glitter.height) / 70; k++) {
240
- const x = rnd() * glitter.width;
241
- const y = rnd() * glitter.height;
333
+ for (let k = 0; k < (w * h) / 70; k++) {
334
+ const x = rnd() * w;
335
+ const y = rnd() * h;
242
336
  g.fillStyle = `rgb(255 255 255 / ${0.2 + rnd() ** 2.5 * 0.8})`;
243
337
  const size = rnd() < 0.9 ? dpr : dpr * 1.6;
244
338
  g.fillRect(x, y, size, size);
245
339
  }
246
340
  }
247
- stars = Array.from({ length: Math.round(((c.width * c.height) / 9000) * STARS) }, () => ({
248
- x: rnd() * c.width,
249
- y: rnd() * c.height,
250
- r: 0.6 + rnd() ** 4 * 3.4,
341
+ stars = Array.from({ length: Math.round(((w * h) / (dpr * dpr * 9000)) * STARS) }, () => ({
342
+ x: rnd() * w,
343
+ y: rnd() * h,
344
+ r: (0.6 + rnd() ** 4 * 3.4) * dpr,
251
345
  phase: rnd() * Math.PI * 2,
252
346
  rate: 0.6 + rnd() * 1.8,
253
347
  cross: rnd() < 0.12,
254
- tint: Math.floor(rnd() * 64),
348
+ tint: rnd(),
255
349
  }));
256
350
  };
257
351
 
258
352
  /**
259
- * One frame: the nebula drifting, the glitter shimmering over it, the
260
- * stars twinkling.
353
+ * One frame, in device px: the nebula drifting, the glitter shimmering
354
+ * over it, the stars twinkling.
261
355
  *
262
356
  * @param {import('./canvas2d.js').Canvas2D} c The canvas.
263
357
  * @param {number} now The time, ms.
264
358
  */
265
359
  const draw = (c, now) => {
266
- const { ctx, width: w, height: h } = c;
360
+ const { ctx, dpr } = c;
361
+ const w = c.canvas.width;
362
+ const h = c.canvas.height;
267
363
  const t = c.still ? 0 : ((now - start) / 1000) * SPEED;
364
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
268
365
  // The nebula, scaled to cover with a margin to drift through.
269
366
  const k = Math.max(w / NEBULA_WIDTH, h / NEBULA_HEIGHT) * 1.12;
270
367
  const nw = NEBULA_WIDTH * k;
@@ -279,22 +376,23 @@ export function galaxy(el, config) {
279
376
  ctx.globalCompositeOperation = 'lighter';
280
377
  if (glitter && GLITTER > 0) {
281
378
  ctx.globalAlpha = Math.min(1, (0.75 + Math.sin(t * 1.7) * 0.12) * GLITTER);
282
- ctx.drawImage(glitter, 0, 0, w, h);
379
+ ctx.drawImage(glitter, 0, 0);
283
380
  }
284
- const hair = 1 / dpr;
285
381
  for (const s of stars) {
286
382
  const a = 0.35 + 0.65 * (0.5 + 0.5 * Math.sin(s.phase + t * s.rate));
287
383
  ctx.globalAlpha = a;
288
- ctx.drawImage(sprites[s.tint % sprites.length], s.x - s.r * 4, s.y - s.r * 4, s.r * 8, s.r * 8);
384
+ starGlow(ctx, s.x, s.y, s.r * 4, tints[Math.floor(s.tint * tints.length)]);
289
385
  if (s.cross) {
386
+ // A cross of light, a CSS px thick.
290
387
  ctx.fillStyle = '#ffffff';
291
388
  const arm = s.r * 9 * a;
292
- ctx.fillRect(s.x - arm, s.y - hair / 2, arm * 2, hair);
293
- ctx.fillRect(s.x - hair / 2, s.y - arm, hair, arm * 2);
389
+ ctx.fillRect(s.x - arm, s.y - dpr * 0.5, arm * 2, dpr);
390
+ ctx.fillRect(s.x - dpr * 0.5, s.y - arm, dpr, arm * 2);
294
391
  }
295
392
  }
296
393
  ctx.globalAlpha = 1;
297
394
  ctx.globalCompositeOperation = 'source-over';
395
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
298
396
  };
299
397
 
300
398
  const { c, stop } = createCanvas2D(el, { draw, resize });