@mathzetta/qblur 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,601 @@
1
+ # qblur on your own pages
2
+
3
+ qblur is the library behind [the editor](https://qblur.com/): image filters written as maths, compiled to
4
+ WebGL shaders, with the same pixels from plain JavaScript where there is no GPU. Put it on any page
5
+ with one `<script>` from a CDN — no build step, no server, nothing uploaded: the pictures stay in the
6
+ visitor's browser.
7
+
8
+ ## What you can do with it
9
+
10
+ - **Filters on your pictures, live.** Any `<img>`, `<canvas>`, `<video>` or webcam — sepia, blur,
11
+ comic, tilt-shift, a colour splash, or one of your own in a line of maths: `1 - rgb`,
12
+ `if gray > 0.5 then (1, 0, 0) else rgb`, `mix(rgb, gaussian(4), y)`.
13
+ - **Knobs.** A filter declares its parameters (`strength`, `tint`, …) with ranges; your sliders set them
14
+ and the picture redraws at once, without recompiling.
15
+ - **79 ready-made filters** in `LIBRARY`, in seven groups (colour and tone, blur and edges, shape and
16
+ motion, text, brushes, other pictures, chains) — use them as they are, chain them, or read their maths.
17
+ - **Chains.** Filters run one after another, each with its own settings and opacity; a chain is a filter
18
+ too, so published chains nest and keep their authors' names.
19
+ - **Animation.** `t` counts frames: `pixel(px + 8 sin(py / 10 + t / 5), py)` is a wave. On a video, the
20
+ filter runs on every frame.
21
+ - **Several pictures.** Masks, overlays, a second photo to blend in, a background for a green screen —
22
+ each placed (cover, fit, tile, zoomed, turned) and set by name.
23
+ - **Text and shapes** drawn into the picture and coloured, shadowed, frosted or animated by the maths.
24
+ - **Share a filter as a link** or a small JSON document; reading one is safe — a filter is only maths:
25
+ it can read the picture and write colours, nothing else.
26
+ - **Save the result** as PNG (in Node too), JPEG, WebP or an animated GIF.
27
+ - **GPU or CPU, the same pixels.** WebGL when it is there (fast: the shaders are compiled once), plain
28
+ JavaScript when it isn't — old browsers, locked-down machines, **Node** (thumbnails on a server, tests).
29
+
30
+ Some things people build with it: filters on upload in a photo or social app; effects on a `<video>` or a
31
+ webcam stream; a product page that recolours an item as the customer picks; generative art and
32
+ animated backgrounds; previews in a CMS; high-contrast or colour-blindness views for accessibility; a
33
+ lesson on how pictures are just numbers. The [small apps](https://qblur.com/avatar/) on qblur.com —
34
+ profile picture, colour splash, make it move, fancy text — are each a page of this library and a few
35
+ controls.
36
+
37
+ ## Start here
38
+
39
+ ### One line: applyFilter
40
+
41
+ ```html runnable
42
+ <img id="photo" src="photo.jpg" alt="" hidden>
43
+ <canvas id="out"></canvas>
44
+ <script src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.global.min.js"></script>
45
+ <script>
46
+ const img = document.getElementById('photo');
47
+ img.decode().then(() => QBlur.applyFilter(img, 'Sepia', { canvas: document.getElementById('out') }));
48
+ </script>
49
+ ```
50
+
51
+ `applyFilter(picture, filter, options)` takes the filter in any form — maths (`'1 - rgb'`), a built-in
52
+ filter's name (`'Sepia'`, `'Gaussian blur'`), a filter document, JSON, a share link or a compiled filter —
53
+ and resolves with the result at the picture's size: a 2D canvas (yours, given as `canvas`, or a new one) in a
54
+ page, `{ data, width, height }` in Node. A picture longer than 4096 px on its long side (2048 on the CPU) is
55
+ scaled down to that first, keeping its shape — `maxSize` sets the limit, up to what the GPU can hold. Knobs go in `params` (in a chain, every step with a knob of that
56
+ name takes it), the frame in `t`. Calls run one at a time, in the order they were made:
57
+
58
+ ```js
59
+ import { applyFilter, toBlob } from '@mathzetta/qblur/apply'; // its own entry; the classic scripts have it on window.QBlur
60
+
61
+ const canvas = await applyFilter(img, 'Threshold', { params: { cutoff: 0.3 } });
62
+ const frame = await applyFilter(video, 'pixel(px + 8 sin(py / 10 + t / 5), py)', { t: 12 });
63
+ ```
64
+
65
+ It uses the GPU when WebGL is there and the CPU when it isn't (`engine: 'gpu' | 'cpu'` to choose), keeps
66
+ one hidden WebGL canvas for every call, and compiles a filter once for all the calls that use it. For a
67
+ picture that redraws many times a second as a knob moves, a runner of your own (below) skips the copy.
68
+
69
+ ### As an HTML element
70
+
71
+ ```html runnable
72
+ <qblur-image id="out" src="photo.jpg" filter="Vignette" params='{"strength": 2.5}' alt="A street of coloured houses"></qblur-image>
73
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur-element.js"></script>
74
+ ```
75
+
76
+ `<qblur-image>` draws its picture with the filter on it, and again whenever an attribute changes:
77
+ `src`, `filter` (any form `applyFilter` takes), `params` (JSON, or set the `params` property to an object: whichever was set last counts),
78
+ `t`, `animate` (present: `t` counts up, 30 a second, while the element is in view), `engine`, `alt` and `crossorigin` (as on `<img>`: a
79
+ picture from another site must allow CORS). It fires `load` after each drawing and `error` (the Error in
80
+ `event.detail`) when the picture or the filter fails; `element.canvas` is the drawing, for
81
+ [saving](#saving-the-result). From npm: `import '@mathzetta/qblur/element'`.
82
+
83
+ ### One script tag, a runner of your own
84
+
85
+ ```html runnable
86
+ <img id="photo" src="photo.jpg" alt="">
87
+ <canvas id="out"></canvas>
88
+ <script src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.global.min.js"></script>
89
+ <script>
90
+ const img = document.getElementById('photo'), canvas = document.getElementById('out');
91
+ img.decode().then(() => {
92
+ canvas.width = img.naturalWidth; // the result is the canvas's size: make it the picture's
93
+ canvas.height = img.naturalHeight;
94
+ const compiled = QBlur.compileFilter('1 - rgb'); // a filter: here, one line of maths
95
+ const { runner } = QBlur.createRunner(compiled, { gl: canvas.getContext('webgl') });
96
+ runner.setImage(img).draw({ canvas }); // the GPU draws on gl's canvas; without WebGL, the CPU draws on `canvas`
97
+ });
98
+ </script>
99
+ ```
100
+
101
+ The classic build puts everything on `window.QBlur`. `createRunner` picks the GPU when the canvas gives
102
+ a WebGL context and the CPU when it doesn't; pass the same canvas to `draw` either way.
103
+
104
+ ### An ES module, a library filter and a slider
105
+
106
+ ```html runnable
107
+ <canvas id="out"></canvas>
108
+ <label>Vignette <input id="strength" type="range" min="0" max="4" step="0.01" value="1.6"></label>
109
+ <script type="module">
110
+ import { compileFilter, createRunner, LIBRARY } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.js';
111
+
112
+ const img = new Image();
113
+ img.src = 'photo.jpg';
114
+ await img.decode();
115
+ const canvas = document.getElementById('out');
116
+ canvas.width = img.naturalWidth;
117
+ canvas.height = img.naturalHeight;
118
+
119
+ const byName = (name) => LIBRARY.find((f) => f.name === name);
120
+ const compiled = compileFilter({ steps: [byName('Sepia'), byName('Vignette')] }); // a chain of two
121
+ const { runner } = createRunner(compiled, { gl: canvas.getContext('webgl') });
122
+ runner.setImage(img).draw({ canvas });
123
+
124
+ // knobs change live: set the value on every pass that has it, and draw again (no recompiling)
125
+ document.getElementById('strength').oninput = (e) => {
126
+ for (const pass of runner.passes) if ('strength' in pass.params) pass.values.strength = Number(e.target.value);
127
+ runner.draw({ canvas });
128
+ };
129
+ </script>
130
+ ```
131
+
132
+ ### From npm
133
+
134
+ ```bash
135
+ npm install @mathzetta/qblur mathzetta # mathzetta is a peer dependency: qblur uses its maths parser and GLSL output
136
+ ```
137
+
138
+ ```js
139
+ import { compileFilter, createRunner } from '@mathzetta/qblur'; // the filters, the runners, the library
140
+ import { applyFilter, toBlob } from '@mathzetta/qblur/apply'; // one call, and saving
141
+ import '@mathzetta/qblur/element'; // defines <qblur-image>
142
+ ```
143
+
144
+ A bundler (Vite, esbuild, webpack, rollup) handles the rest. TypeScript types come with the package (`src/index.d.ts`, `src/apply.d.ts`, `src/element.d.ts`). In Node the CPU runner works as it is (see
145
+ [In Node](#in-node)).
146
+
147
+ ### Which file
148
+
149
+ Every release has these in `dist/` (sizes compressed, as the CDN sends them):
150
+
151
+ | File | Size | What |
152
+ | --- | --- | --- |
153
+ | `qblur.js` | 54 KB | ES module, everything but `@mathzetta/qblur/apply`, MathZetta inside |
154
+ | `qblur.global.min.js` | 58 KB | a classic script: `window.QBlur`, everything — `applyFilter` and saving too |
155
+ | `qblur-apply.js` | 56 KB | ES module: `@mathzetta/qblur/apply` (`applyFilter`, `toBlob`, `encodeGif`…), MathZetta inside |
156
+ | `qblur.core.js` | 33 KB | compile and run on the GPU only: `compileFilter`, `createFilterRunner`, `readFilter`, `filterToLink`, `normalizeFilter` — no CPU runner, library, text or brushes |
157
+ | `qblur.external.js` | 26 KB | `qblur.js` with MathZetta left out: the page provides it (an import map) |
158
+ | `qblur.external.global.min.js` | 30 KB | `qblur.global.min.js` without MathZetta: reads `window.MathZetta`, so a MathZetta script goes first |
159
+ | `qblur-element.js` | 56 KB | `<qblur-image>`, with `applyFilter` and MathZetta inside |
160
+ | `cpu-worker.js` | 31 KB | the CPU runner's helper for big pictures (`drawAsync`), loaded only when used; it must sit beside the bundle (it does on the CDN) |
161
+
162
+ MathZetta is about half of a full build. A page that already uses MathZetta, or several libraries built on
163
+ it, loads it once and takes the `external` build. With modules, an import map points every MathZetta name
164
+ at one file:
165
+
166
+ ```html runnable
167
+ <canvas id="out"></canvas>
168
+ <script type="importmap">
169
+ { "imports": {
170
+ "mathzetta": "https://cdn.jsdelivr.net/npm/mathzetta@1/build/mathzetta.esm.min.js",
171
+ "mathzetta/glsl": "https://cdn.jsdelivr.net/npm/mathzetta@1/build/mathzetta.esm.min.js",
172
+ "mathzetta/formulas": "https://cdn.jsdelivr.net/npm/mathzetta@1/build/mathzetta.esm.min.js"
173
+ } }
174
+ </script>
175
+ <script type="module">
176
+ import { compileFilter, createRunner } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.external.js';
177
+ const img = new Image();
178
+ img.src = 'photo.jpg';
179
+ await img.decode();
180
+ const canvas = document.getElementById('out');
181
+ canvas.width = img.naturalWidth;
182
+ canvas.height = img.naturalHeight;
183
+ const { runner } = createRunner(compileFilter('(gray, gray, gray)'), { gl: canvas.getContext('webgl') });
184
+ runner.setImage(img).draw({ canvas });
185
+ </script>
186
+ ```
187
+
188
+ With classic scripts: `<script src="…/mathzetta@1/build/mathzetta.glsl.min.js">` (the GLSL flavour, which
189
+ is what filters use) and then `…/@mathzetta/qblur@0.1/dist/qblur.external.global.min.js`.
190
+
191
+ Pin a version (`@0.1` follows fixes, `@0.1.0` never changes) and, for a fixed version, add an `integrity`
192
+ hash so the browser checks the file. jsDelivr shows each file's hash on its package page, or make it
193
+ yourself: `curl -s https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1.0/dist/qblur.js | openssl dgst -sha384 -binary | openssl base64 -A`
194
+ gives the part after `sha384-`.
195
+
196
+ ## Filters
197
+
198
+ A filter is maths run on every pixel. The [guide](filters.md) is the full language — what an expression
199
+ can use, animation, neighbouring pixels, geometry, several pictures, colour spaces, text and brushes. In
200
+ short: `r g b a` (or `rgb`) is the pixel, `x y` its position from 0 to 1, `px py` in pixels, `w h` the
201
+ picture's size, `t` the frame, `gray` its brightness, `source` the original picture, and
202
+ `pixel(px, py)` reads another pixel. The result is a colour `(r, g, b)` or a number (grey).
203
+
204
+ What you pass to `compileFilter`:
205
+
206
+ ```js
207
+ compileFilter('1 - rgb'); // an expression
208
+ compileFilter({ // a filter document
209
+ name: 'Threshold', author: 'Ada', description: 'Black or white',
210
+ params: { cutoff: { default: 0.5, min: 0, max: 1 } }, // a knob
211
+ color: 'if gray > cutoff then 1 else 0',
212
+ });
213
+ compileFilter({ // a chain: steps run top to bottom
214
+ name: 'Old photo',
215
+ steps: [
216
+ LIBRARY.find((f) => f.name === 'Sepia'), // a filter as it is
217
+ { filter: LIBRARY.find((f) => f.name === 'Vignette'), with: { strength: 1.2 } }, // with its knob set
218
+ { filter: 'rgb * 1.1', opacity: 0.5 }, // half strength
219
+ { filter: 'gaussian(2)', skip: true }, // left out for now
220
+ ],
221
+ });
222
+ ```
223
+
224
+ The fields of a filter document:
225
+
226
+ | Field | What |
227
+ | --- | --- |
228
+ | `format` | `"mathzetta-filter/1"` — optional when writing one; `filterToJSON` adds it. The format is frozen: later versions add, never change |
229
+ | `name`, `author`, `description` | shown in credits and the editor's library |
230
+ | `params` | knobs: `{ name: { default, min, max, step?, label? } }`; a colour is `[r, g, b]` (0–1) or `{ type: 'color', default: [r, g, b] }`; a bare number is a default |
231
+ | `color` | the maths: a string, or by channel — `{ rgb: '…', a: '…' }`, `{ r, g, b, a }`, `{ rgba: '…' }` |
232
+ | `space` | the colour space the maths works in: `'hsv'`, `'hsl'`, `'lab'`, `'oklab'`, `'linear'`, `'ycbcr'`, or `{ in, out }` |
233
+ | `images` | other pictures it reads, by name: `{ mask: { description: 'light where the effect shows' } }` |
234
+ | `graphics` | text, rectangles, ovals or brush strokes drawn into pictures it reads ([Text and shapes](#text-and-shapes)) |
235
+ | `steps` | a chain instead of `color`: each step a filter (or an expression), with `with`, `opacity` and `skip` |
236
+
237
+ ## Running a filter
238
+
239
+ ### compileFilter
240
+
241
+ ```js
242
+ const compiled = compileFilter(def, { version: 100 }); // 100: WebGL 1 (the default); 300: WebGL 2
243
+ compiled.passes; // one shader pass per filter in the chain, in order; each has params, values, images, placements
244
+ compiled.images; // every picture it needs, by name
245
+ compiled.graphics; // every graphic, by name
246
+ compiled.credits; // [{ name: 'Sepia', author: '' }, …] — the filters it is made of
247
+ ```
248
+
249
+ It throws when the filter is malformed or its maths doesn't parse:
250
+ `the filter: Failed to parse expression "rgb * (1, 2": …`. A name the maths doesn't know (`rgb * nope`) is
251
+ found when a runner is made: `unknown name "nope"`. `validateFilter(def)` lists every problem with the
252
+ document itself, as messages naming the filter (`"Vignette": "with" sets "nope", but there is no parameter
253
+ called that`), without throwing.
254
+
255
+ ### createRunner: the GPU, or the CPU
256
+
257
+ ```js
258
+ const { runner, engine, reason } = createRunner(compiled, {
259
+ gl: canvas.getContext('webgl'), // null or missing: the CPU
260
+ prefer: 'auto', // 'gpu' or 'cpu' to insist
261
+ precision: 'byte', // 'half' or 'float' keeps values over 1 between passes (bloom, edges)
262
+ });
263
+ engine; // 'gpu' or 'cpu'
264
+ reason; // why: 'WebGL is here', 'no WebGL here', 'the GPU refused the shader (…)', 'asked for the CPU'
265
+ ```
266
+
267
+ Both runners have the same methods:
268
+
269
+ | | |
270
+ | --- | --- |
271
+ | `runner.setImage(picture)` | the picture to filter: `<img>`, `<canvas>`, `<video>`, `ImageData`, `ImageBitmap`, or `{ data, width, height }`. Call it again for each new picture or video frame. Returns the runner |
272
+ | `runner.setImage(name, picture)` | another picture the filter names (`compiled.images`, graphics) |
273
+ | `runner.draw({ t, canvas })` | runs every pass. The GPU draws on the canvas `gl` belongs to; the CPU draws on `canvas` when given, and returns `{ data, width, height }` (RGBA bytes) |
274
+ | `runner.passes` | `compiled.passes`, live: `passes[i].values.cutoff = 0.3`, then `draw()` |
275
+ | `runner.dispose()` | frees the textures and programs (or the CPU's workers) |
276
+
277
+ The output is the canvas's size (GPU) or the picture's size (CPU), and the picture is stretched to it — so
278
+ **size the canvas to the picture**, or to the size you want to save.
279
+
280
+ ### On the GPU: createFilterRunner
281
+
282
+ ```js
283
+ const gl = canvas.getContext('webgl', { preserveDrawingBuffer: true, premultipliedAlpha: false });
284
+ const runner = createFilterRunner(gl, compiled, { precision: 'half' });
285
+ runner.precision; // what the GPU gave: 'byte', 'half' or 'float'
286
+ ```
287
+
288
+ - `preserveDrawingBuffer: true` keeps the result on the canvas after the frame, so `canvas.toBlob()` can save
289
+ it later (otherwise call it straight after `draw()`).
290
+ - `premultipliedAlpha: false` keeps transparent results (`a` below 1) as they are.
291
+ - WebGL 2: `canvas.getContext('webgl2')` and `compileFilter(def, { version: 300 })`.
292
+ - The browser can take the context away (a GPU reset, a sleeping laptop): listen for `webglcontextlost`
293
+ (call `preventDefault()`), and on `webglcontextrestored` make a new runner.
294
+ - Pictures from another site need `img.crossOrigin = 'anonymous'` **and** that site's CORS header, or WebGL
295
+ refuses them (the same rule as reading a canvas's pixels).
296
+
297
+ ### On the CPU: createCpuRunner
298
+
299
+ ```js
300
+ const runner = createCpuRunner(compiled, { precision: 'byte', workers: 'auto', parallelFrom: 250000 });
301
+ const out = runner.setImage(img).draw({ t: 0, canvas }); // on this thread
302
+ const out2 = await runner.drawAsync({ t: 0, canvas }); // big pictures: rows shared among workers
303
+ ```
304
+
305
+ `drawAsync` splits each pass's rows among workers (`cpu-worker.js` beside the bundle — on the CDN it is;
306
+ `workerUrl` puts it elsewhere) when the picture has at least `parallelFrom` pixels, and draws on the calling
307
+ thread when it doesn't or when workers can't start. Both give the same pixels, and the same as the GPU.
308
+
309
+ ### In Node
310
+
311
+ The CPU runner needs no browser:
312
+
313
+ ```js node
314
+ import { compileFilter, createCpuRunner, LIBRARY } from '@mathzetta/qblur';
315
+
316
+ // a 64 × 64 picture as RGBA bytes — in practice, decoded from a file (sharp, pngjs, …)
317
+ const width = 64, height = 64, data = new Uint8ClampedArray(width * height * 4);
318
+ for (let i = 0; i < width * height; i++) data.set([(i % width) * 4, 120, 200, 255], i * 4);
319
+
320
+ const sepia = LIBRARY.find((f) => f.name === 'Sepia');
321
+ const runner = createCpuRunner(compileFilter(sepia));
322
+ const out = runner.setImage({ data, width, height }).draw();
323
+ console.log(out.width, out.height, out.data.slice(0, 4)); // 64 64 Uint8ClampedArray [ … ]
324
+ ```
325
+
326
+ With [sharp](https://sharp.pixelplumbing.com/) for the files:
327
+
328
+ ```js
329
+ const { data, info } = await sharp('in.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
330
+ const out = createCpuRunner(compileFilter('1 - rgb')).setImage({ data: new Uint8ClampedArray(data), width: info.width, height: info.height }).draw();
331
+ await sharp(Buffer.from(out.data), { raw: { width: out.width, height: out.height, channels: 4 } }).toFile('out.png');
332
+ ```
333
+
334
+ ## Knobs
335
+
336
+ `filterParams(normalizeFilter(def))` lists every knob a filter or chain has —
337
+ `{ strength: { type: 'number', default: 1.6, min: 0, max: 4 } }`, colours as `{ type: 'color', default: [r, g, b] }` —
338
+ so a page can build its controls from the filter:
339
+
340
+ ```html runnable
341
+ <canvas id="out"></canvas>
342
+ <form id="knobs"></form>
343
+ <script type="module">
344
+ import { compileFilter, createRunner, normalizeFilter, filterParams } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.js';
345
+
346
+ const def = {
347
+ name: 'Duotone',
348
+ params: { dark: [0.1, 0.05, 0.3], light: [1, 0.8, 0.4], contrast: { default: 1, min: 0.5, max: 2, label: 'Contrast' } },
349
+ color: 'mix(dark, light, clamp((gray - 0.5) contrast + 0.5, 0, 1))',
350
+ };
351
+ const img = new Image();
352
+ img.src = 'photo.jpg';
353
+ await img.decode();
354
+ const canvas = document.getElementById('out');
355
+ canvas.width = img.naturalWidth;
356
+ canvas.height = img.naturalHeight;
357
+ const { runner } = createRunner(compileFilter(def), { gl: canvas.getContext('webgl') });
358
+ runner.setImage(img).draw({ canvas });
359
+
360
+ const set = (name, value) => {
361
+ for (const pass of runner.passes) if (name in pass.params) pass.values[name] = value;
362
+ runner.draw({ canvas });
363
+ };
364
+ const hex = (rgb) => '#' + rgb.map((v) => Math.round(v * 255).toString(16).padStart(2, '0')).join('');
365
+ const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16) / 255);
366
+ for (const [name, p] of Object.entries(filterParams(normalizeFilter(def)))) {
367
+ const input = document.createElement('input');
368
+ if (p.type === 'color') { input.type = 'color'; input.value = hex(p.default); input.oninput = () => set(name, rgb(input.value)); }
369
+ else Object.assign(input, { type: 'range', min: p.min, max: p.max, step: p.step ?? (p.max - p.min) / 200, value: p.default, oninput: () => set(name, Number(input.value)) });
370
+ const label = document.createElement('label');
371
+ label.append(p.label ?? name, ' ', input);
372
+ document.getElementById('knobs').append(label);
373
+ }
374
+ </script>
375
+ ```
376
+
377
+ In a chain, `filterParams` gives each knob's own default; the values a chain sets with `with` are in
378
+ `compiled.passes[i].values`.
379
+
380
+ ## Animation, video and the webcam
381
+
382
+ `t` is whatever you pass to `draw`. Count frames for an animation:
383
+
384
+ ```html runnable
385
+ <canvas id="out"></canvas>
386
+ <script type="module">
387
+ import { compileFilter, createRunner } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.js';
388
+ const img = new Image();
389
+ img.src = 'photo.jpg';
390
+ await img.decode();
391
+ const canvas = document.getElementById('out');
392
+ canvas.width = img.naturalWidth;
393
+ canvas.height = img.naturalHeight;
394
+ const { runner } = createRunner(compileFilter('pixel(px + 6 sin(py / 12 + t / 5), py)'), { gl: canvas.getContext('webgl') });
395
+ runner.setImage(img); // a still picture: set it once
396
+ let t = 0;
397
+ (function frame() { runner.draw({ t: t++, canvas }); requestAnimationFrame(frame); })();
398
+ </script>
399
+ ```
400
+
401
+ A video is a picture that changes: give the runner each frame.
402
+
403
+ ```html runnable
404
+ <video id="clip" src="clip.mp4" muted loop playsinline autoplay hidden></video>
405
+ <canvas id="out"></canvas>
406
+ <script type="module">
407
+ import { compileFilter, createRunner } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.js';
408
+ const video = document.getElementById('clip'), canvas = document.getElementById('out');
409
+ await new Promise((r) => { video.onloadeddata = r; if (video.readyState >= 2) r(); });
410
+ canvas.width = video.videoWidth;
411
+ canvas.height = video.videoHeight;
412
+ const { runner } = createRunner(compileFilter('(red(px + 6, py), g, blue(px - 6, py))'), { gl: canvas.getContext('webgl') });
413
+ let t = 0;
414
+ const frame = () => {
415
+ runner.setImage(video).draw({ t: t++, canvas });
416
+ video.requestVideoFrameCallback ? video.requestVideoFrameCallback(frame) : requestAnimationFrame(frame);
417
+ };
418
+ frame();
419
+ </script>
420
+ ```
421
+
422
+ The webcam is the same with `video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true })`.
423
+ To save what is shown as a video: `new MediaRecorder(canvas.captureStream(30))`.
424
+
425
+ ## Other pictures: masks, overlays, backgrounds
426
+
427
+ A filter names the pictures it reads in `images`; the maths uses them by name — `mask` is its colour at
428
+ this pixel, `luma(mask)` its brightness, `alpha(mask)` its transparency — and you give them with
429
+ `setImage(name, picture)`. A picture not given is white.
430
+
431
+ ```html runnable
432
+ <canvas id="out"></canvas>
433
+ <script type="module">
434
+ import { compileFilter, createRunner, LIBRARY } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.js';
435
+ const img = new Image();
436
+ img.src = 'photo.jpg';
437
+ await img.decode();
438
+ const canvas = document.getElementById('out');
439
+ canvas.width = img.naturalWidth;
440
+ canvas.height = img.naturalHeight;
441
+
442
+ // a spotlight mask: light in the middle, dark at the edges
443
+ const mask = Object.assign(document.createElement('canvas'), { width: 256, height: 256 });
444
+ const g = mask.getContext('2d'), grad = g.createRadialGradient(128, 128, 20, 128, 128, 128);
445
+ grad.addColorStop(0, '#fff'); grad.addColorStop(1, '#000');
446
+ g.fillStyle = grad; g.fillRect(0, 0, 256, 256);
447
+
448
+ // grey everywhere, colour where the mask is light ("Through a mask" is mix(source, rgb, luma(mask)))
449
+ const byName = (name) => LIBRARY.find((f) => f.name === name);
450
+ const { runner } = createRunner(compileFilter({ steps: [byName('Grayscale'), byName('Through a mask')] }), { gl: canvas.getContext('webgl') });
451
+ runner.setImage(img).setImage('mask', mask).draw({ canvas });
452
+ </script>
453
+ ```
454
+
455
+ A picture of another shape is placed over the frame: `cover` (the default), `fit`, `stretch` or `tile`,
456
+ with `zoom`, `x`, `y` and `angle` — set per step (`{ filter, with: { overlay: { place: 'fit', zoom: 0.5 } } }`)
457
+ or live (`runner.passes[i].placements.overlay.x = 0.2`; changing `place` needs a new compile).
458
+ `selected` is the picture named `selection` (the editor's selection): give it a mask to limit a filter to
459
+ part of the picture.
460
+
461
+ ## Text and shapes
462
+
463
+ A filter's `graphics` are drawn into pictures of the frame's size, which the maths reads like any other
464
+ picture. `renderGraphics` draws them (loading web fonts first); positions and sizes are fractions of the
465
+ frame, so they are crisp at any size.
466
+
467
+ ```html runnable
468
+ <canvas id="out"></canvas>
469
+ <script type="module">
470
+ import { compileFilter, createRunner, renderGraphics } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.js';
471
+ const img = new Image();
472
+ img.src = 'photo.jpg';
473
+ await img.decode();
474
+ const canvas = document.getElementById('out');
475
+ canvas.width = img.naturalWidth;
476
+ canvas.height = img.naturalHeight;
477
+
478
+ const compiled = compileFilter({
479
+ graphics: { title: { type: 'text', text: 'Hello!', size: 0.16, y: 0.5, color: '#ffd23f' } },
480
+ color: 'mix(rgb * 0.6, title, alpha(title))', // the picture darkened, the words laid on it
481
+ });
482
+ const { runner } = createRunner(compiled, { gl: canvas.getContext('webgl') });
483
+ runner.setImage(img);
484
+ for (const [key, picture] of Object.entries(await renderGraphics(compiled, canvas.width, canvas.height))) runner.setImage(key, picture);
485
+ runner.draw({ canvas });
486
+ </script>
487
+ ```
488
+
489
+ Text has `text`, `font` (a CSS family, or `fontUrl` for a web font), `weight`, `style`, `size`, `x`, `y`,
490
+ `align`, `angle`, `color`, `outline` and shadows; `rect` and `ellipse` have `x`, `y` (the centre), `w`, `h`,
491
+ `angle`, `color`, `outline` and shadows, and a rectangle a corner `radius`. Brush strokes (`type: 'strokes'`) are recorded drawings that play out over `t`; draw them
492
+ for each frame with `renderGraphics(compiled, w, h, { t })` or `rasterizeStrokes`. The guide's
493
+ "Text and shapes" and "Brushes" have every field.
494
+
495
+ ## Saving the result
496
+
497
+ ```js
498
+ const png = await toBlob(canvas); // a PNG: indexed when there are ≤ 256 colours, RGB when opaque
499
+ const jpeg = await toBlob(canvas, { type: 'image/jpeg', quality: 0.9 }); // JPEG and WebP: the browser's encoder
500
+ const { data, width, height } = cpuRunner.draw(); // CPU: the bytes themselves
501
+ ```
502
+
503
+ `toBlob` takes a 2D canvas (what `applyFilter` returns) or a picture `{ data, width, height }`, and writes
504
+ PNG itself, so it works in Node as well; JPEG and WebP need a browser. A WebGL canvas can't be read back
505
+ with a 2D context: pass the canvas `applyFilter` gave you, or call the canvas's own `toBlob` right after
506
+ `draw()` (or create the context with `preserveDrawingBuffer: true`).
507
+
508
+ An animated GIF needs a colour quantizer and an LZW encoder. The package has no dependencies, so bring
509
+ [gifenc](https://www.npmjs.com/package/gifenc) (`npm i gifenc`, 9 KB) and pass it in:
510
+
511
+ ```js node
512
+ import * as gifenc from 'gifenc';
513
+ import { applyFilter, encodeGif, toBlob } from '@mathzetta/qblur/apply';
514
+
515
+ const picture = { width: 64, height: 48, data: new Uint8ClampedArray(64 * 48 * 4).fill(200) };
516
+ const frames = [];
517
+ for (let t = 0; t < 10; t++) frames.push(await applyFilter(picture, '(x, y, 0.5 + 0.5 sin(t / 2))', { t }));
518
+ const gif = await encodeGif(frames, { gifenc, delay: 50 }); // 50 ms a frame, looping
519
+ const png = await toBlob(frames[0]); // PNG in Node: no canvas needed
520
+ console.log(gif.type, gif.size, png.type);
521
+ ```
522
+
523
+ Frames can be canvases or pictures, all one size, in an array or an async iterable (each frame drawn as it
524
+ is needed); `repeat: -1` plays once. To save at a different size than you show, draw into a second canvas
525
+ of that size, or with the CPU runner on a picture of that size.
526
+
527
+ ## Sharing filters
528
+
529
+ ```js
530
+ const link = filterToLink(def, 'https://qblur.com/'); // https://qblur.com/#eyJmb3Jt… — opens in the editor
531
+ const json = filterToJSON(def); // the document, defaults left out
532
+ readFilter(text); // whatever was pasted: a link, JSON, or an expression
533
+ filterFromLink(location.hash); // a filter from your own page's address
534
+ validateFilter(readFilter(text)); // [] when it is fine
535
+ ```
536
+
537
+ A filter from someone else is safe to run: it is maths over the picture, compiled by qblur into shaders (or
538
+ checked JavaScript on the CPU), with no access to the page, the network or anything else. One thing does reach
539
+ the network: a filter with text may name a font (a Google Fonts family or an https address), which the page
540
+ then fetches to draw it — so whoever serves that font sees the request.
541
+
542
+ ## The built-in library
543
+
544
+ `LIBRARY` is an array of filter documents (79), each with a `group` from `GROUPS`:
545
+
546
+ ```js
547
+ GROUPS; // ['Colour & tone', 'Blur & edges', 'Shape & motion', 'Text & shapes', 'Brushes', 'Other pictures', 'Chains']
548
+ LIBRARY.filter((f) => f.group === 'Blur & edges').map((f) => f.name);
549
+ const comic = LIBRARY.find((f) => f.name === 'Comic'); // a chain of four
550
+ ```
551
+
552
+ The editor's [library](https://qblur.com/) shows them all on your own photo, with their maths.
553
+
554
+ ## Reference
555
+
556
+ Everything the package exports — from `@mathzetta/qblur/apply`, the first seven; from `@mathzetta/qblur/element`, `QBlurImage`; from
557
+ `@mathzetta/qblur`, the rest:
558
+
559
+ | Export | What |
560
+ | --- | --- |
561
+ | `applyFilter(picture, filter, { params, t, images, engine, canvas, maxSize })` | the one call: the filtered picture (a 2D canvas, or `{ data, width, height }` in Node), at most `maxSize` on its long side; the filter in any form, or a `LIBRARY` name |
562
+ | `MAX_SIZE`, `MAX_SIZE_CPU` | the default `maxSize`: 4096 on the GPU, 2048 on the CPU |
563
+ | `toCompiled(filter)` | any form `applyFilter` takes → the compiled filter |
564
+ | `toBlob(canvasOrPicture, { type, quality, palette })` | the result as a file: PNG anywhere, JPEG and WebP in a browser |
565
+ | `encodeGif(frames, { gifenc, delay, repeat, colours })` | an animated GIF, with gifenc passed in |
566
+ | `encodePng({ width, height, data, palette, colours, quantize })` | the PNG writer `toBlob` uses (indexed, RGB or RGBA) |
567
+ | `pictureData(canvasOrPicture)` | its RGBA bytes |
568
+ | `QBlurImage` (from `@mathzetta/qblur/element`) | the `<qblur-image>` element's class; importing the entry defines the element |
569
+ | `compileFilter(def, { version })` | a filter (expression, document or chain) → `{ passes, images, graphics, credits, … }`; throws on a malformed filter or maths that doesn't parse |
570
+ | `createRunner(compiled, { gl, prefer, precision, workers })` | `{ runner, engine, reason }`: the GPU when `gl` is a WebGL context, else the CPU |
571
+ | `createFilterRunner(gl, compiled, { precision })` | the WebGL runner |
572
+ | `createCpuRunner(compiled, { precision, workers, parallelFrom, workerUrl })` | the JavaScript runner (browsers and Node); `draw()` and `drawAsync()` |
573
+ | `chooseEngine({ webgl, prefer })` | which runner `createRunner` would use, and why |
574
+ | `toPicture(image)` | any picture as `{ data: Float32Array, width, height }` (what the CPU works on) |
575
+ | `normalizeFilter(def)` | the full form: types and ranges on params, `with` and `opacity` on steps; throws on a bad shape |
576
+ | `validateFilter(def)` | every problem, as messages naming the filter; `[]` when it will compile |
577
+ | `filterParams(filter)` / `filterImages(filter)` / `filterGraphics(filter)` | a normalized filter's knobs, pictures, graphics (a chain's included) |
578
+ | `filterToJSON(def)` / `filterFromJSON(text)` | the document as JSON, and back |
579
+ | `filterToLink(def, pageUrl)` / `filterFromLink(text)` | the filter in a URL's `#…`, and back |
580
+ | `readFilter(text)` | a link, JSON or a bare expression → a filter |
581
+ | `FILTER_FORMAT`, `PLACEMENT` | `'mathzetta-filter/1'`; the default placement `{ place: 'cover', zoom: 1, x: 0.5, y: 0.5, angle: 0 }` |
582
+ | `LIBRARY`, `GROUPS` | the built-in filters and their groups |
583
+ | `renderGraphics(compiled, w, h, { t, mask })` | every graphic drawn at w × h → `{ key: picture }` for `setImage` |
584
+ | `normalizeGraphic`, `drawGraphic(ctx, spec, w, h)`, `loadGraphicFonts`, `cssFont`, `GRAPHIC_TYPES`, `GRAPHIC_DEFAULTS` | text and shapes, one at a time |
585
+ | `googleFontUrl(family)`, `googleFontFamily(url)`, `fontFileFromCss`, `familyFor` | web fonts for text graphics |
586
+ | `shadowLayerNames`, `layeredExpression`, `MAX_SHADOW_LAYERS` | text shadows as pictures of their own |
587
+ | `normalizeStrokes`, `strokeTimeline`, `rasterizeStrokes(spec, w, h, t, { mask })` | brush strokes, frame by frame |
588
+ | `BRUSHES`, `TIMINGS`, `WIDTH_FROM`, `CLIPS`, `FPS`, `STROKES_DEFAULTS` | brush options |
589
+ | `traceContours(mask, w, h)`, `simplify`, `simplifyLoop` | the outlines of a mask, as polylines |
590
+ | `compileCpuPass(pass)` | one pass as checked JavaScript (what the CPU runner runs; `.uses` says if it reads `t`, other pictures, `random`) |
591
+
592
+ ## Good to know
593
+
594
+ - **Sizes in pixels stay pixels.** `gaussian(4)` blurs 4 pixels whatever the picture's size, so effects look
595
+ finer on a bigger picture; scale such numbers with `w` or `h` (`gaussian(w / 200)`) to keep a look at any size.
596
+ - **Between passes the picture is 8-bit**, as an image is: values clamp to 0–1. `precision: 'half'` keeps
597
+ more where the effect needs it (bloom, edge strengths).
598
+ - **Big pictures.** WebGL limits a texture to `gl.getParameter(gl.MAX_TEXTURE_SIZE)` (often 4096 or more);
599
+ the CPU has no limit but takes longer — `drawAsync` uses every core.
600
+ - **Licence.** MIT ([LICENSE](https://github.com/triplelog/qblur/blob/main/LICENSE), Copyright (c) 2025-2026 Robert Wilcox), and so is
601
+ MathZetta, which the bundles include. The object models used by the editor's "find objects" are not in the package.