img-auto-parallax 0.0.0 → 0.1.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/README.md CHANGED
@@ -1,14 +1,10 @@
1
1
  # img-auto-parallax
2
2
 
3
- A drop-in `<img>` replacement that estimates depth on the GPU and shifts the scene's layers as you hover, or as you tilt your phone. Without WebGPU, or with `disabled`, it is simply the image.
3
+ A drop-in `<img>` that estimates depth on the GPU and gives any photo parallax as you hover or tilt your phone. Without WebGPU, it is simply the image.
4
4
 
5
- - **Drop-in**: forwards every `<img>` attribute (`src`, `srcset`, `alt`, `loading`, `width`/`height`…) and sizes like an image.
6
- - **Graceful**: plain image until depth is ready; stays a plain image without WebGPU or for non-CORS images.
7
- - **Self-contained**: ships Depth Anything V2 small and FastDepth, so no third-party model host is needed by default.
8
- - **GPU-resident**: ONNX Runtime Web on WebGPU; depth never round-trips through the CPU ([vgpu](https://vgpu.sh) wraps the output buffer).
9
- - **Configurable**: strength, focus depth, depth-of-field, smoothing, trigger (hover / gyro / manual), idle sway, invert, resolution, three built-in models or your own.
5
+ [![img-auto-parallax: a plain image beside the same photo with depth and parallax](https://img-auto-parallax.vercel.app/og.gif)](https://img-auto-parallax.vercel.app)
10
6
 
11
- ## Install
7
+ **[Documentation & playground →](https://img-auto-parallax.vercel.app)** · **[Watch the intro video ▶](https://img-auto-parallax.vercel.app/intro.mp4)**
12
8
 
13
9
  ```sh
14
10
  pnpm add img-auto-parallax
@@ -19,59 +15,15 @@ import 'img-auto-parallax/define'
19
15
  ```
20
16
 
21
17
  ```html
22
- <img-auto-parallax src="/photo.jpg" alt="A mountain lake" width="1280" height="960"></img-auto-parallax>
18
+ <img-auto-parallax src="/photo.jpg" alt="A mountain lake"></img-auto-parallax>
23
19
  ```
24
20
 
25
- With Vite, keep the package out of dependency pre-bundling so the bundled model and ONNX Runtime's `.wasm` resolve:
21
+ Powered by [vgpu](https://vgpu.sh) by Vercel.
26
22
 
27
- ```ts
28
- export default defineConfig({
29
- optimizeDeps: {
30
- exclude: ['img-auto-parallax', 'onnxruntime-web']
31
- },
32
- })
33
- ```
34
-
35
- ## Attributes
36
-
37
- | Attribute | Default | Description |
38
- | --- | --- | --- |
39
- | `disabled` | `false` | Behave exactly like `<img>`. |
40
- | `strength` | `0.05` | Max displacement, fraction of image height (0–0.3). |
41
- | `focus-depth` | `0.5` | Depth that stays still: 0 background … 1 foreground. |
42
- | `smoothing` | `150` | Easing time constant in ms. |
43
- | `trigger` | `auto` | `auto` · `hover` · `gyro` · `both` · `manual`. |
44
- | `idle` | `none` | `sway` drifts gently while idle. |
45
- | `invert` | `false` | Reverse the motion. |
46
- | `resolution` | `518` | Long side of the model input in px. |
47
- | `model` | `configure()` | `depth-anything` (bundled), `midas` (on demand), `fastdepth` (bundled), or a `registerModel()` name. |
48
- | `view` | `image` | `depth` shows the depth map. |
49
- | `defocus` | `0` | Depth of field (0–1); focus follows what is under the pointer. |
50
-
51
- The smoothed pointer is exposed as `--img-auto-parallax-x` / `--img-auto-parallax-y` (−1…1) for custom effects, plus `data-active` while someone is steering. Style the inner image and canvas with `::part(img | canvas)`.
52
-
53
- Methods: `setPointer(x, y)` / `setPointer(null)`, `refresh()`. State: `state` / `data-state` (`static` · `loading` · `ready` · `unsupported` · `error`). Events: `load`, `error`, `parallax-ready`, `parallax-error`.
54
-
55
- ## Configuration
56
-
57
- ```ts
58
- import { configure, defineImgAutoParallax, preload } from 'img-auto-parallax'
59
-
60
- configure({
61
- model: 'depth-anything', // default for elements without `model`; can change any time
62
- onProgress: ({ loaded, total }) => {},
63
- })
64
- defineImgAutoParallax() // or defineImgAutoParallax('my-tag')
65
- preload() // optional: start loading before an image is visible
66
- ```
67
-
68
- Built-in models:
23
+ ## Requirements
69
24
 
70
- | Name | Model | Size | Source |
71
- | --- | --- | --- | --- |
72
- | `depth-anything` | Depth Anything V2 small (Apache-2.0) | 19 MB | bundled (q4f16); GPUs without `shader-f16` load the 27 MB q4 build from Hugging Face |
73
- | `midas` | MiDaS v2.1 small (MIT) | 64 MB | loaded on demand from vgpu.sh |
74
- | `fastdepth` | FastDepth (MIT) | 5 MB | bundled |
25
+ - **HTTPS**: WebGPU (and motion events) only exist in secure contexts. Serve over `https://`, or `localhost` in development; otherwise images stay plain.
26
+ - **Gyro permission**: iOS Safari asks before sharing device motion, and only from a user gesture. A tap on an image asks automatically; to ask yourself, use `getGyroPermission()` and `requestGyroPermission()` from a click handler.
75
27
 
76
28
  ## Development
77
29
 
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/cli.mjs ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import process from "node:process";
3
+ import { parseArgs } from "node:util";
4
+ import { r as precompute } from "./node-Cgcvci4U.mjs";
5
+ // src/cli.ts
6
+ /**
7
+ * img-auto-parallax precompute <patterns...> [--model name] [--resolution n|full] [--suffix s] [--force]
8
+ */
9
+ const HELP = `Usage: img-auto-parallax precompute <patterns...> [options]
10
+
11
+ Generate depth maps (photo.jpg -> photo.depth.png) for <img-auto-parallax src-depth>.
12
+
13
+ Options:
14
+ --model <name> depth-anything (default) | midas | fastdepth
15
+ --resolution <px> model input long side (default 518), or "full" (slow; output is 1:1 regardless)
16
+ --suffix <suffix> output suffix (default .depth.png)
17
+ --force regenerate even when up to date
18
+ -h, --help show this help
19
+ `;
20
+ async function main() {
21
+ const { values, positionals } = parseArgs({
22
+ allowPositionals: true,
23
+ options: {
24
+ model: { type: "string" },
25
+ resolution: { type: "string" },
26
+ suffix: { type: "string" },
27
+ force: { type: "boolean" },
28
+ help: {
29
+ type: "boolean",
30
+ short: "h"
31
+ }
32
+ }
33
+ });
34
+ const [command, ...patterns] = positionals;
35
+ if (values.help || command !== "precompute" || patterns.length === 0) {
36
+ process.stdout.write(HELP);
37
+ process.exitCode = values.help ? 0 : 1;
38
+ return;
39
+ }
40
+ const started = performance.now();
41
+ const result = await precompute(patterns, {
42
+ model: values.model,
43
+ resolution: values.resolution && values.resolution !== "full" ? Number(values.resolution) : void 0,
44
+ suffix: values.suffix,
45
+ force: values.force,
46
+ onProgress: ({ output, status, index, total }) => {
47
+ process.stdout.write(`[${index + 1}/${total}] ${status === "cached" ? "cached " : "generated"} ${output}\n`);
48
+ }
49
+ });
50
+ const seconds = ((performance.now() - started) / 1e3).toFixed(1);
51
+ process.stdout.write(`${result.generated.length} generated, ${result.cached.length} up to date, in ${seconds}s\n`);
52
+ }
53
+ main().catch((error) => {
54
+ console.error(error);
55
+ process.exitCode = 1;
56
+ });
57
+ export {};
package/dist/define.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { n as defineImgAutoParallax } from "./src-DHNTwA54.mjs";
1
+ import { n as defineImgAutoParallax } from "./src-CLDV9piW.mjs";
2
2
  // src/define.ts
3
3
  defineImgAutoParallax();
package/dist/index.d.mts CHANGED
@@ -1,18 +1,37 @@
1
1
  import "vgpu";
2
2
  /**
3
- * - `static` plain image: disabled, or not scrolled into view yet
3
+ * - `static` plain image: disabled, or out of view (GPU resources released)
4
4
  * - `loading` estimating depth for the current image (or loading the model)
5
5
  * - `ready` parallax active
6
6
  * - `unsupported` no WebGPU, or the model failed to load: plain image
7
7
  * - `error` this image could not be used (e.g. cross-origin without CORS): plain image
8
8
  */
9
9
  type ParallaxState = 'static' | 'loading' | 'ready' | 'unsupported' | 'error';
10
- /** What drives the parallax. `auto`: gyro on touch devices, hover elsewhere. */
11
- type ParallaxTrigger = 'auto' | 'hover' | 'gyro' | 'both' | 'manual';
10
+ /**
11
+ * What drives the parallax:
12
+ * - `self-hover`: the pointer over this image
13
+ * - `page-hover`: the pointer anywhere on the page, relative to this image
14
+ * - `gyro`: device tilt
15
+ * - `both`: self-hover and gyro
16
+ * - `manual`: only `setPointer()`
17
+ * - `auto` (default): gyro on touch devices, self-hover elsewhere
18
+ *
19
+ * Combine them with spaces, e.g. `trigger="page-hover gyro"`.
20
+ */
21
+ type ParallaxTrigger = 'auto' | 'self-hover' | 'page-hover' | 'gyro' | 'both' | 'manual' | (string & {});
12
22
  /** Motion when nobody is interacting. */
13
23
  type ParallaxIdle = 'none' | 'sway';
14
24
  /** What the canvas shows: the photo, or the estimated depth (near = bright). */
15
25
  type ParallaxView = 'image' | 'depth';
26
+ /**
27
+ * What the element draws:
28
+ * - `image` (default): the photo with depth parallax
29
+ * - `foreground`: only what is nearer than `cutoff`, transparent elsewhere
30
+ * - `flat`: the whole photo moving rigidly with a `foreground` copy, as the plate behind it
31
+ * - `background`: only what is farther than `cutoff`, the foreground filled in from
32
+ * around it, moving at its own depth so a `foreground` copy slides over it
33
+ */
34
+ type ParallaxLayer = 'image' | 'foreground' | 'flat' | 'background';
16
35
  export declare const DEFAULTS: {
17
36
  strength: number;
18
37
  focusDepth: number;
@@ -22,6 +41,8 @@ export declare const DEFAULTS: {
22
41
  idle: ParallaxIdle;
23
42
  view: ParallaxView;
24
43
  defocus: number;
44
+ layer: ParallaxLayer;
45
+ cutoff: number;
25
46
  };
26
47
  /**
27
48
  * `<img-auto-parallax>`: an `<img>` that estimates depth on the GPU and
@@ -45,9 +66,15 @@ export declare class ImgAutoParallaxElement extends HTMLElement {
45
66
  get disabled(): boolean;
46
67
  set disabled(value: boolean);
47
68
  /** Model for this element: `auto`, a preset (`q4f16`, `q4`, `fp16`, `fp32`) or a registered name. Defaults to `configure({ model })`. */
69
+ /**
70
+ * A precompiled depth map (grayscale, near = bright, any size), e.g. from
71
+ * `img-auto-parallax precompute`. When set, no model or ONNX Runtime is loaded.
72
+ */
73
+ get srcDepth(): string | null;
74
+ set srcDepth(value: string | null | undefined);
48
75
  get model(): string | null;
49
76
  set model(value: string | null);
50
- /** Maximum displacement as a fraction of the image height (0–0.3, default 0.05). */
77
+ /** Maximum displacement as a fraction of the image height (0–0.3, default 0.03). */
51
78
  get strength(): number;
52
79
  set strength(value: number);
53
80
  /** Nearness of the plane that stays still: 0 = background, 1 = foreground (default 0.5). */
@@ -77,6 +104,20 @@ export declare class ImgAutoParallaxElement extends HTMLElement {
77
104
  */
78
105
  get defocus(): number;
79
106
  set defocus(value: number);
107
+ /** Bring the whole image back into focus while the pointer is not over it (depth of field only while hovering). */
108
+ get refocus(): boolean;
109
+ set refocus(value: boolean);
110
+ /**
111
+ * `foreground` draws only what is nearer than `cutoff`; `flat` draws the whole photo
112
+ * moving in lockstep with it; `background` draws the rest, with the foreground filled
113
+ * in, moving less, so the subject separates from it. Stack `flat` or `background`, your
114
+ * content, then `foreground` to tuck content behind the subject, like a lock-screen depth effect.
115
+ */
116
+ get layer(): ParallaxLayer;
117
+ set layer(value: ParallaxLayer);
118
+ /** Nearness threshold between `layer="foreground"` and `layer="background"` (0–1, default 0.6). */
119
+ get cutoff(): number;
120
+ set cutoff(value: number);
80
121
  /** Current lifecycle state; also reflected as the `data-state` attribute. */
81
122
  get state(): ParallaxState;
82
123
  /**
@@ -90,6 +131,24 @@ export declare class ImgAutoParallaxElement extends HTMLElement {
90
131
  disconnectedCallback(): void;
91
132
  attributeChangedCallback(name: string, old: string | null, value: string | null): void;
92
133
  }
134
+ /** True on devices without a hovering pointer that expose orientation events. */
135
+ export declare function prefersGyro(): boolean;
136
+ /** Called when `getGyroPermission()` changes, e.g. after a grant or once readings arrive. */
137
+ export declare function onGyroPermissionChange(listener: (permission: GyroPermission) => void): () => void;
138
+ /**
139
+ * Gyro access on this device:
140
+ * - `unavailable`: no orientation events (most desktops)
141
+ * - `prompt`: the browser asks first (iOS Safari); call `requestGyroPermission()` from a tap
142
+ * - `granted` / `denied`: the answer, for this page load
143
+ * - `not-required`: events flow without asking (Android, most others)
144
+ */
145
+ type GyroPermission = 'unavailable' | 'prompt' | 'granted' | 'denied' | 'not-required';
146
+ export declare function getGyroPermission(): GyroPermission;
147
+ /**
148
+ * Ask for gyro access. Must run inside a user gesture (a tap or click handler),
149
+ * or iOS rejects it. Elements start following the tilt as soon as it is granted.
150
+ */
151
+ export declare function requestGyroPermission(): Promise<GyroPermission>;
93
152
  /** Describes an ONNX depth model the runtime can drive. */
94
153
  interface DepthModelSpec {
95
154
  /** Location of the `.onnx` file. */
@@ -184,4 +243,4 @@ declare global {
184
243
  'img-auto-parallax': ImgAutoParallaxElement;
185
244
  }
186
245
  }
187
- export type { DepthModelOption, DepthModelPreset, DepthModelSpec, ImgAutoParallaxConfig, ModelProgress, ParallaxIdle, ParallaxState, ParallaxTrigger, ParallaxView };
246
+ export type { DepthModelOption, DepthModelPreset, DepthModelSpec, GyroPermission, ImgAutoParallaxConfig, ModelProgress, ParallaxIdle, ParallaxLayer, ParallaxState, ParallaxTrigger, ParallaxView };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { r as DEFAULTS, l as DEFAULT_MODEL, t as DEFAULT_TAG, i as ImgAutoParallaxElement, u as MODEL_PRESETS, a as configure, n as defineImgAutoParallax, o as hasWebGpu, s as isSupported, d as listModels, c as preload, f as registerModel } from "./src-DHNTwA54.mjs";
1
+ export { r as DEFAULTS, l as DEFAULT_MODEL, t as DEFAULT_TAG, i as ImgAutoParallaxElement, u as MODEL_PRESETS, a as configure, n as defineImgAutoParallax, p as getGyroPermission, o as hasWebGpu, s as isSupported, d as listModels, m as onGyroPermissionChange, h as prefersGyro, c as preload, f as registerModel, g as requestGyroPermission } from "./src-CLDV9piW.mjs";
@@ -0,0 +1,95 @@
1
+ /** Describes an ONNX depth model the runtime can drive. */
2
+ interface DepthModelSpec {
3
+ /** Location of the `.onnx` file. */
4
+ url: string | URL;
5
+ /** Graph input name (NCHW float32). */
6
+ inputName: string;
7
+ /** Graph output name (float32, `[1, H, W]` or `[1, 1, H, W]`). */
8
+ outputName: string;
9
+ /**
10
+ * Input sizes are rounded to a multiple of this (the ViT patch size for
11
+ * Depth Anything). Ignored when `fixedSize` is set.
12
+ */
13
+ multiple?: number;
14
+ /** Fixed `[width, height]` input. When omitted, the input follows each image's aspect ratio. */
15
+ fixedSize?: readonly [number, number];
16
+ /** How RGB is normalised before inference: ImageNet mean/std, or plain 0–1. */
17
+ normalization: 'imagenet' | 'unit';
18
+ /**
19
+ * How to read the output. `relative`: larger values are nearer (inverse
20
+ * depth, auto-ranged per image). `metric`: metres, mapped with a log scale.
21
+ */
22
+ output: {
23
+ kind: 'relative';
24
+ } | {
25
+ kind: 'metric';
26
+ near: number;
27
+ far: number;
28
+ };
29
+ /** Needs the WebGPU `shader-f16` feature (fp16 weights). */
30
+ requiresF16?: boolean;
31
+ /** Used instead when `requiresF16` is set and the GPU lacks `shader-f16`. */
32
+ fallback?: DepthModelSpec;
33
+ /** Human-readable name, for pickers and logs. */
34
+ label?: string;
35
+ /** Download size in bytes, when known. */
36
+ bytes?: number;
37
+ }
38
+ type DepthModelPreset = 'depth-anything' | 'midas' | 'fastdepth';
39
+ /** A preset or registered name, or a full spec. */
40
+ type DepthModelOption = DepthModelPreset | (string & {}) | DepthModelSpec;
41
+ /** Conventional depth map path for an image: `photo.jpg` → `photo.depth.png`. */
42
+ declare function depthMapPath(image: string, suffix?: string): string;
43
+ interface DepthMapOptions {
44
+ /** Model to use (default `depth-anything`). Must match what looks right for your photos. */
45
+ model?: DepthModelOption;
46
+ /**
47
+ * Long side of the model input in px (default 518, what Depth Anything is
48
+ * trained at), or `'full'` for the image's own size up to 2048 px. The output
49
+ * map is always 1:1 with the photo either way; `'full'` is ~60× slower, needs
50
+ * gigabytes of memory, and usually comes out softer. Ignored by fixed-size models.
51
+ */
52
+ resolution?: number | 'full';
53
+ }
54
+ interface DepthMap {
55
+ width: number;
56
+ height: number;
57
+ /** Grayscale PNG, near = bright. */
58
+ png: Uint8Array;
59
+ }
60
+ interface DecodedImage {
61
+ width: number;
62
+ height: number;
63
+ data: Uint8Array;
64
+ }
65
+ /** Decode a JPEG or PNG to RGBA. */
66
+ declare function decodeImage(bytes: Uint8Array): DecodedImage;
67
+ /** Run the depth model on an image (JPEG/PNG bytes) on the CPU, and encode the depth map. */
68
+ declare function generateDepthMap(image: Uint8Array, options?: DepthMapOptions): Promise<DepthMap>;
69
+ interface PrecomputeOptions extends DepthMapOptions {
70
+ /** Base directory for relative patterns (default `process.cwd()`). */
71
+ cwd?: string;
72
+ /** Output suffix replacing the extension (default `.depth.png`). */
73
+ suffix?: string;
74
+ /** Regenerate even when the depth map is up to date. */
75
+ force?: boolean;
76
+ /** Where to keep the cache manifest (default `node_modules/.cache/img-auto-parallax.json` under `cwd`). */
77
+ cacheFile?: string;
78
+ onProgress?: (event: {
79
+ file: string;
80
+ output: string;
81
+ status: 'generated' | 'cached';
82
+ index: number;
83
+ total: number;
84
+ }) => void;
85
+ }
86
+ interface PrecomputeResult {
87
+ generated: string[];
88
+ cached: string[];
89
+ }
90
+ /**
91
+ * Generate `photo.depth.png` next to every matching image. Unchanged images
92
+ * (same content, model and resolution) are skipped.
93
+ */
94
+ declare function precompute(patterns: string | string[], options?: PrecomputeOptions): Promise<PrecomputeResult>;
95
+ export { decodeImage as a, depthMapPath as c, PrecomputeResult as i, DepthMapOptions as n, generateDepthMap as o, PrecomputeOptions as r, precompute as s, DepthMap as t };