@paper-design/shaders 0.0.0-canary.b7acb21 → 0.0.0-canary.df082ba

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.
Files changed (47) hide show
  1. package/dist/html-in-canvas.d.ts +23 -0
  2. package/dist/html-in-canvas.js +64 -0
  3. package/dist/html-in-canvas.js.map +7 -0
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.js +4 -0
  6. package/dist/index.js.map +2 -2
  7. package/dist/shader-mount.d.ts +16 -1
  8. package/dist/shader-mount.js +143 -26
  9. package/dist/shader-mount.js.map +2 -2
  10. package/dist/shaders/color-panels.js +0 -3
  11. package/dist/shaders/color-panels.js.map +2 -2
  12. package/dist/shaders/dot-orbit.js +1 -2
  13. package/dist/shaders/dot-orbit.js.map +2 -2
  14. package/dist/shaders/fluted-glass.d.ts +4 -1
  15. package/dist/shaders/fluted-glass.js +18 -18
  16. package/dist/shaders/fluted-glass.js.map +2 -2
  17. package/dist/shaders/god-rays.js +3 -5
  18. package/dist/shaders/god-rays.js.map +2 -2
  19. package/dist/shaders/halftone-cmyk.d.ts +4 -2
  20. package/dist/shaders/halftone-cmyk.js +34 -8
  21. package/dist/shaders/halftone-cmyk.js.map +2 -2
  22. package/dist/shaders/halftone-dots.d.ts +4 -2
  23. package/dist/shaders/halftone-dots.js +30 -5
  24. package/dist/shaders/halftone-dots.js.map +2 -2
  25. package/dist/shaders/image-dithering.d.ts +5 -3
  26. package/dist/shaders/image-dithering.js +20 -4
  27. package/dist/shaders/image-dithering.js.map +2 -2
  28. package/dist/shaders/lens-distortion.d.ts +3 -1
  29. package/dist/shaders/lens-distortion.js +14 -7
  30. package/dist/shaders/lens-distortion.js.map +2 -2
  31. package/dist/shaders/liquid-metal.js +1 -2
  32. package/dist/shaders/liquid-metal.js.map +2 -2
  33. package/dist/shaders/paper-texture.d.ts +5 -1
  34. package/dist/shaders/paper-texture.js +34 -21
  35. package/dist/shaders/paper-texture.js.map +2 -2
  36. package/dist/shaders/voronoi.js +1 -2
  37. package/dist/shaders/voronoi.js.map +2 -2
  38. package/dist/shaders/water.d.ts +4 -2
  39. package/dist/shaders/water.js +23 -8
  40. package/dist/shaders/water.js.map +2 -2
  41. package/dist/size-to-content.d.ts +8 -0
  42. package/dist/size-to-content.js +41 -0
  43. package/dist/size-to-content.js.map +7 -0
  44. package/dist/vertex-shader.d.ts +1 -1
  45. package/dist/vertex-shader.js +3 -0
  46. package/dist/vertex-shader.js.map +2 -2
  47. package/package.json +1 -1
@@ -0,0 +1,23 @@
1
+ /**
2
+ * https://github.com/WICG/html-in-canvas
3
+ *
4
+ * An HTML uniform has to be in this markup already, `layoutsubtree` is for older Chromium:
5
+ *
6
+ * <div data-paper-shader>
7
+ * <canvas content="drawable" layoutsubtree>
8
+ * <div drawable>…</div>
9
+ * </canvas>
10
+ * </div>
11
+ */
12
+ export interface DrawableCanvasElement extends HTMLCanvasElement {
13
+ requestPaint(): void;
14
+ updateElementGeometry(element: Element, options?: {
15
+ canvasTransform?: DOMMatrixInit;
16
+ }): void;
17
+ }
18
+ export declare function isHtmlInCanvasSupported(): boolean;
19
+ /** nodeType, since `instanceof` fails across iframes */
20
+ export declare function isHtmlUniform(value: unknown): value is HTMLElement;
21
+ export declare function findDrawableCanvas(values: unknown[], parentElement: Element): DrawableCanvasElement | null;
22
+ /** Captures the element into the bound texture, returns the layout to pass back in next time */
23
+ export declare function drawHtml(gl: WebGL2RenderingContext, canvas: DrawableCanvasElement, element: HTMLElement, lastLayout?: string): string;
@@ -0,0 +1,64 @@
1
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * *
2
+ * Paper Shaders *
3
+ * https://github.com/paper-design/shaders *
4
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * */
5
+
6
+ function isHtmlInCanvasSupported() {
7
+ return typeof HTMLCanvasElement !== "undefined" && "requestPaint" in HTMLCanvasElement.prototype && typeof WebGL2RenderingContext !== "undefined" && "texElementSubImage2D" in WebGL2RenderingContext.prototype;
8
+ }
9
+ function isHtmlUniform(value) {
10
+ return value?.nodeType === 1 && value.tagName !== "IMG";
11
+ }
12
+ function findDrawableCanvas(values, parentElement) {
13
+ for (const value of values) {
14
+ const canvas = isHtmlUniform(value) ? value.parentElement : null;
15
+ if (canvas?.tagName === "CANVAS" && canvas.parentElement === parentElement) {
16
+ return canvas;
17
+ }
18
+ }
19
+ return null;
20
+ }
21
+ function drawHtml(gl, canvas, element, lastLayout) {
22
+ const width = Math.max(1, canvas.width);
23
+ const height = Math.max(1, canvas.height);
24
+ const canvasStyle = getComputedStyle(canvas);
25
+ const elementStyle = getComputedStyle(element);
26
+ const canvasCssWidth = parseFloat(canvasStyle.width) || canvas.clientWidth;
27
+ const canvasCssHeight = parseFloat(canvasStyle.height) || canvas.clientHeight;
28
+ const elementCssWidth = parseFloat(elementStyle.width) || element.offsetWidth;
29
+ const elementCssHeight = parseFloat(elementStyle.height) || element.offsetHeight;
30
+ const scaleX = width / Math.max(1, canvasCssWidth);
31
+ const scaleY = height / Math.max(1, canvasCssHeight);
32
+ const left = element.offsetLeft;
33
+ const top = element.offsetTop;
34
+ const visibleLeft = Math.max(0, left);
35
+ const visibleTop = Math.max(0, top);
36
+ const visibleRight = Math.min(canvasCssWidth, left + elementCssWidth);
37
+ const visibleBottom = Math.min(canvasCssHeight, top + elementCssHeight);
38
+ const x0 = Math.round(visibleLeft * scaleX);
39
+ const y0 = Math.round(visibleTop * scaleY);
40
+ const x1 = Math.min(width, Math.round(visibleRight * scaleX));
41
+ const y1 = Math.min(height, Math.round(visibleBottom * scaleY));
42
+ const layout = `${width}x${height} ${x0},${y0},${x1},${y1}`;
43
+ if (layout !== lastLayout) {
44
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
45
+ }
46
+ if (x1 > x0 && y1 > y0) {
47
+ gl.texElementSubImage2D(gl.TEXTURE_2D, 0, x0, y0, element, {
48
+ sx: visibleLeft - left,
49
+ sy: visibleTop - top,
50
+ swidth: visibleRight - visibleLeft,
51
+ sheight: visibleBottom - visibleTop,
52
+ width: x1 - x0,
53
+ height: y1 - y0
54
+ });
55
+ }
56
+ return layout;
57
+ }
58
+ export {
59
+ drawHtml,
60
+ findDrawableCanvas,
61
+ isHtmlInCanvasSupported,
62
+ isHtmlUniform
63
+ };
64
+ //# sourceMappingURL=html-in-canvas.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/html-in-canvas.ts"],
4
+ "sourcesContent": ["/**\n * https://github.com/WICG/html-in-canvas\n *\n * An HTML uniform has to be in this markup already, `layoutsubtree` is for older Chromium:\n *\n * <div data-paper-shader>\n * <canvas content=\"drawable\" layoutsubtree>\n * <div drawable>\u2026</div>\n * </canvas>\n * </div>\n */\n\nexport interface DrawableCanvasElement extends HTMLCanvasElement {\n requestPaint(): void;\n updateElementGeometry(element: Element, options?: { canvasTransform?: DOMMatrixInit }): void;\n}\n\ninterface DrawableCanvasWebGL2Context extends WebGL2RenderingContext {\n texElementSubImage2D(\n target: GLenum,\n level: GLint,\n xoffset: GLint,\n yoffset: GLint,\n element: Element,\n config?: { width?: number; height?: number; sx?: number; sy?: number; swidth?: number; sheight?: number }\n ): void;\n}\n\nexport function isHtmlInCanvasSupported(): boolean {\n return (\n typeof HTMLCanvasElement !== 'undefined' &&\n 'requestPaint' in HTMLCanvasElement.prototype &&\n typeof WebGL2RenderingContext !== 'undefined' &&\n 'texElementSubImage2D' in WebGL2RenderingContext.prototype\n );\n}\n\n/** nodeType, since `instanceof` fails across iframes */\nexport function isHtmlUniform(value: unknown): value is HTMLElement {\n return (value as Node | null | undefined)?.nodeType === 1 && (value as Element).tagName !== 'IMG';\n}\n\nexport function findDrawableCanvas(values: unknown[], parentElement: Element): DrawableCanvasElement | null {\n for (const value of values) {\n const canvas = isHtmlUniform(value) ? value.parentElement : null;\n if (canvas?.tagName === 'CANVAS' && canvas.parentElement === parentElement) {\n return canvas as DrawableCanvasElement;\n }\n }\n return null;\n}\n\n/** Captures the element into the bound texture, returns the layout to pass back in next time */\nexport function drawHtml(\n gl: WebGL2RenderingContext,\n canvas: DrawableCanvasElement,\n element: HTMLElement,\n lastLayout?: string\n): string {\n const width = Math.max(1, canvas.width);\n const height = Math.max(1, canvas.height);\n\n // Offset and client sizes are rounded, bounding rects include ancestor transforms\n const canvasStyle = getComputedStyle(canvas);\n const elementStyle = getComputedStyle(element);\n const canvasCssWidth = parseFloat(canvasStyle.width) || canvas.clientWidth;\n const canvasCssHeight = parseFloat(canvasStyle.height) || canvas.clientHeight;\n const elementCssWidth = parseFloat(elementStyle.width) || element.offsetWidth;\n const elementCssHeight = parseFloat(elementStyle.height) || element.offsetHeight;\n const scaleX = width / Math.max(1, canvasCssWidth);\n const scaleY = height / Math.max(1, canvasCssHeight);\n\n const left = element.offsetLeft;\n const top = element.offsetTop;\n const visibleLeft = Math.max(0, left);\n const visibleTop = Math.max(0, top);\n const visibleRight = Math.min(canvasCssWidth, left + elementCssWidth);\n const visibleBottom = Math.min(canvasCssHeight, top + elementCssHeight);\n const x0 = Math.round(visibleLeft * scaleX);\n const y0 = Math.round(visibleTop * scaleY);\n const x1 = Math.min(width, Math.round(visibleRight * scaleX));\n const y1 = Math.min(height, Math.round(visibleBottom * scaleY));\n\n const layout = `${width}x${height} ${x0},${y0},${x1},${y1}`;\n if (layout !== lastLayout) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n }\n\n if (x1 > x0 && y1 > y0) {\n (gl as DrawableCanvasWebGL2Context).texElementSubImage2D(gl.TEXTURE_2D, 0, x0, y0, element, {\n sx: visibleLeft - left,\n sy: visibleTop - top,\n swidth: visibleRight - visibleLeft,\n sheight: visibleBottom - visibleTop,\n width: x1 - x0,\n height: y1 - y0,\n });\n }\n\n return layout;\n}\n"],
5
+ "mappings": ";;;;;AA4BO,SAAS,0BAAmC;AACjD,SACE,OAAO,sBAAsB,eAC7B,kBAAkB,kBAAkB,aACpC,OAAO,2BAA2B,eAClC,0BAA0B,uBAAuB;AAErD;AAGO,SAAS,cAAc,OAAsC;AAClE,SAAQ,OAAmC,aAAa,KAAM,MAAkB,YAAY;AAC9F;AAEO,SAAS,mBAAmB,QAAmB,eAAsD;AAC1G,aAAW,SAAS,QAAQ;AAC1B,UAAM,SAAS,cAAc,KAAK,IAAI,MAAM,gBAAgB;AAC5D,QAAI,QAAQ,YAAY,YAAY,OAAO,kBAAkB,eAAe;AAC1E,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,SACd,IACA,QACA,SACA,YACQ;AACR,QAAM,QAAQ,KAAK,IAAI,GAAG,OAAO,KAAK;AACtC,QAAM,SAAS,KAAK,IAAI,GAAG,OAAO,MAAM;AAGxC,QAAM,cAAc,iBAAiB,MAAM;AAC3C,QAAM,eAAe,iBAAiB,OAAO;AAC7C,QAAM,iBAAiB,WAAW,YAAY,KAAK,KAAK,OAAO;AAC/D,QAAM,kBAAkB,WAAW,YAAY,MAAM,KAAK,OAAO;AACjE,QAAM,kBAAkB,WAAW,aAAa,KAAK,KAAK,QAAQ;AAClE,QAAM,mBAAmB,WAAW,aAAa,MAAM,KAAK,QAAQ;AACpE,QAAM,SAAS,QAAQ,KAAK,IAAI,GAAG,cAAc;AACjD,QAAM,SAAS,SAAS,KAAK,IAAI,GAAG,eAAe;AAEnD,QAAM,OAAO,QAAQ;AACrB,QAAM,MAAM,QAAQ;AACpB,QAAM,cAAc,KAAK,IAAI,GAAG,IAAI;AACpC,QAAM,aAAa,KAAK,IAAI,GAAG,GAAG;AAClC,QAAM,eAAe,KAAK,IAAI,gBAAgB,OAAO,eAAe;AACpE,QAAM,gBAAgB,KAAK,IAAI,iBAAiB,MAAM,gBAAgB;AACtE,QAAM,KAAK,KAAK,MAAM,cAAc,MAAM;AAC1C,QAAM,KAAK,KAAK,MAAM,aAAa,MAAM;AACzC,QAAM,KAAK,KAAK,IAAI,OAAO,KAAK,MAAM,eAAe,MAAM,CAAC;AAC5D,QAAM,KAAK,KAAK,IAAI,QAAQ,KAAK,MAAM,gBAAgB,MAAM,CAAC;AAE9D,QAAM,SAAS,GAAG,KAAK,IAAI,MAAM,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE;AACzD,MAAI,WAAW,YAAY;AACzB,OAAG,WAAW,GAAG,YAAY,GAAG,GAAG,OAAO,OAAO,QAAQ,GAAG,GAAG,MAAM,GAAG,eAAe,IAAI;AAAA,EAC7F;AAEA,MAAI,KAAK,MAAM,KAAK,IAAI;AACtB,IAAC,GAAmC,qBAAqB,GAAG,YAAY,GAAG,IAAI,IAAI,SAAS;AAAA,MAC1F,IAAI,cAAc;AAAA,MAClB,IAAI,aAAa;AAAA,MACjB,QAAQ,eAAe;AAAA,MACvB,SAAS,gBAAgB;AAAA,MACzB,OAAO,KAAK;AAAA,MACZ,QAAQ,KAAK;AAAA,IACf,CAAC;AAAA,EACH;AAEA,SAAO;AACT;",
6
+ "names": []
7
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /** The core Shader Mount class. Pass it a parent element and a fragment shader to get started. */
2
2
  export { ShaderMount, isPaperShaderElement } from './shader-mount.js';
3
+ export { isHtmlInCanvasSupported } from './html-in-canvas.js';
4
+ export { observeContentSize, type ShaderSizeToContent } from './size-to-content.js';
3
5
  export type { PaperShaderElement, ShaderMotionParams, ShaderMountUniforms, ShaderPreset, ImageShaderPreset, } from './shader-mount.js';
4
6
  /** Shader sizing options and uniforms */
5
7
  export { defaultObjectSizing, defaultPatternSizing, ShaderFitOptions, type ShaderFit, type ShaderSizingParams, type ShaderSizingUniforms, } from './shader-sizing.js';
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@
4
4
  * * * * * * * * * * * * * * * * * * * * * * * * * * * */
5
5
 
6
6
  import { ShaderMount, isPaperShaderElement } from "./shader-mount.js";
7
+ import { isHtmlInCanvasSupported } from "./html-in-canvas.js";
8
+ import { observeContentSize } from "./size-to-content.js";
7
9
  import {
8
10
  defaultObjectSizing,
9
11
  defaultPatternSizing,
@@ -156,6 +158,7 @@ export {
156
158
  heatmapFragmentShader,
157
159
  heatmapMeta,
158
160
  imageDitheringFragmentShader,
161
+ isHtmlInCanvasSupported,
159
162
  isPaperShaderElement,
160
163
  lensDistortionFragmentShader,
161
164
  lensDistortionMeta,
@@ -165,6 +168,7 @@ export {
165
168
  metaballsFragmentShader,
166
169
  metaballsMeta,
167
170
  neuroNoiseFragmentShader,
171
+ observeContentSize,
168
172
  paperTextureFragmentShader,
169
173
  paperTextureMeta,
170
174
  perlinNoiseFragmentShader,
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["/** The core Shader Mount class. Pass it a parent element and a fragment shader to get started. */\nexport { ShaderMount, isPaperShaderElement } from './shader-mount.js';\nexport type {\n PaperShaderElement,\n ShaderMotionParams,\n ShaderMountUniforms,\n ShaderPreset,\n ImageShaderPreset,\n} from './shader-mount.js';\n\n/** Shader sizing options and uniforms */\nexport {\n defaultObjectSizing,\n defaultPatternSizing,\n ShaderFitOptions,\n type ShaderFit,\n type ShaderSizingParams,\n type ShaderSizingUniforms,\n} from './shader-sizing.js';\n\n/** A flowing interplay of color spots, moving along distinct trajectories and transformed by organic distortion */\nexport {\n meshGradientFragmentShader,\n meshGradientMeta,\n type MeshGradientParams,\n type MeshGradientUniforms,\n} from './shaders/mesh-gradient.js';\n\n/** Radial multi-colored gradient shaped with layered noise for a natural, smoky aesthetic */\nexport {\n smokeRingMeta,\n smokeRingFragmentShader,\n type SmokeRingParams,\n type SmokeRingUniforms,\n} from './shaders/smoke-ring.js';\n\n/** A glowing, web-like structure of fluid lines and soft intersections. Great for creating atmospheric, organic-yet-futuristic visuals */\nexport { neuroNoiseFragmentShader, type NeuroNoiseParams, type NeuroNoiseUniforms } from './shaders/neuro-noise.js';\n\n/** Animated multi-color dots pattern with each dot orbiting around its cell center. Supports up to 40 colors and various shape and motion controls. Great for playful, dynamic backgrounds and UI textures */\nexport {\n dotOrbitMeta,\n dotOrbitFragmentShader,\n type DotOrbitParams,\n type DotOrbitUniforms,\n} from './shaders/dot-orbit.js';\n\n/** Static grid pattern made of circles, diamonds, squares or triangles */\nexport {\n dotGridFragmentShader,\n DotGridShapes,\n type DotGridShape,\n type DotGridParams,\n type DotGridUniforms,\n} from './shaders/dot-grid.js';\n\n/** A multi-color gradient mapped into smooth, animated curves, delivering a sleek, futuristic visual */\nexport {\n simplexNoiseMeta,\n simplexNoiseFragmentShader,\n type SimplexNoiseParams,\n type SimplexNoiseUniforms,\n} from './shaders/simplex-noise.js';\n\n/** Up to 20 gooey blobs moving around the center and merging into smooth organic shapes */\nexport {\n metaballsMeta,\n metaballsFragmentShader,\n type MetaballsParams,\n type MetaballsUniforms,\n} from './shaders/metaballs.js';\n\n/** Animated 3D Perlin noise with exposed controls */\nexport { perlinNoiseFragmentShader, type PerlinNoiseParams, type PerlinNoiseUniforms } from './shaders/perlin-noise.js';\n\n/** Anti-aliased animated Voronoi pattern with smooth and customizable edges */\nexport { voronoiMeta, voronoiFragmentShader, type VoronoiParams, type VoronoiUniforms } from './shaders/voronoi.js';\n\n/** Static line pattern configurable into textures ranging from sharp zigzags to smooth flowing waves */\nexport { wavesFragmentShader, type WavesParams, type WavesUniforms } from './shaders/waves.js';\n\n/** Animated color fields warped by noise and swirls, applied over base patterns (checks, stripes, or split edge). Blends up to 10 colors with adjustable distribution, softness, distortion, and swirl. Great for fluid, smoky, or marbled effects */\nexport {\n warpMeta,\n warpFragmentShader,\n WarpPatterns,\n type WarpParams,\n type WarpUniforms,\n type WarpPattern,\n} from './shaders/warp.js';\n\n/** Animated rays of light radiating from the center, blended with up to 5 colors. The rays are adjustable by size, density, brightness and center glow. Great for dramatic backgrounds, logo reveals, and VFX like energy bursts or sun shafts */\nexport { godRaysMeta, godRaysFragmentShader, type GodRaysParams, type GodRaysUniforms } from './shaders/god-rays.js';\n\n/** A single-colored animated spiral that morphs across a wide range of shapes - from crisp, thin-lined geometry to flowing whirlpool forms and wavy, abstract rings */\nexport { spiralFragmentShader, type SpiralParams, type SpiralUniforms } from './shaders/spiral.js';\n\n/** Animated bands of color twisting and bending, producing spirals, arcs, and flowing circular patterns */\nexport { swirlMeta, swirlFragmentShader, type SwirlParams, type SwirlUniforms } from './shaders/swirl.js';\n\n/** Animated 2-color dithering over with multiple pattern sources (noise, warp, dots, waves, ripple, swirl, sphere) */\nexport {\n ditheringFragmentShader,\n DitheringShapes,\n DitheringTypes,\n type DitheringParams,\n type DitheringUniforms,\n type DitheringShape,\n type DitheringType,\n} from './shaders/dithering.js';\n\n/** Multi-color gradients with grainy, noise-textured distortion available in 7 animated abstract forms */\nexport {\n grainGradientFragmentShader,\n grainGradientMeta,\n GrainGradientShapes,\n type GrainGradientParams,\n type GrainGradientUniforms,\n type GrainGradientShape,\n} from './shaders/grain-gradient.js';\n\n/** Luminous trails of color merging into a glowing gradient frame */\nexport {\n pulsingBorderMeta,\n pulsingBorderFragmentShader,\n PulsingBorderAspectRatios,\n type PulsingBorderParams,\n type PulsingBorderUniforms,\n type PulsingBorderAspectRatio,\n} from './shaders/pulsing-border.js';\n\n/** Glowing translucent 3D panels rotating around a central axis */\nexport {\n colorPanelsFragmentShader,\n colorPanelsMeta,\n type ColorPanelsParams,\n type ColorPanelsUniforms,\n} from './shaders/color-panels.js';\n\n/** Multi-point mesh gradients with up to 10 color spots, enhanced by two-direction warping, adjustable blend sharpness, and grain controls. Perfect for elegant wallpapers and atmospheric backdrops */\nexport {\n staticMeshGradientFragmentShader,\n staticMeshGradientMeta,\n type StaticMeshGradientParams,\n type StaticMeshGradientUniforms,\n} from './shaders/static-mesh-gradient.js';\n\n/** Radial gradient with up to 10 blended colors, featuring advanced focal point control, shape distortion, and grain effects */\nexport {\n staticRadialGradientFragmentShader,\n staticRadialGradientMeta,\n type StaticRadialGradientParams,\n type StaticRadialGradientUniforms,\n} from './shaders/static-radial-gradient.js';\n\n/** A static texture built from multiple noise layers, usable for a realistic paper and cardboard surfaces or generating abstract patterns. Can be used as a image filter or as a texture */\nexport {\n paperTextureFragmentShader,\n paperTextureMeta,\n type PaperTextureParams,\n type PaperTextureUniforms,\n} from './shaders/paper-texture.js';\n\n/** Water-like surface distortion with natural caustic realism. Works as an image filter or animated texture without image */\nexport { waterFragmentShader, type WaterParams, type WaterUniforms } from './shaders/water.js';\n\n/** Fluted glass image filter transforms an image into streaked, ribbed distortions, giving a mix of clarity and obscurity */\nexport {\n flutedGlassFragmentShader,\n GlassDistortionShapes,\n GlassGridShapes,\n type GlassDistortionShape,\n type GlassGridShape,\n type FlutedGlassParams,\n type FlutedGlassUniforms,\n} from './shaders/fluted-glass.js';\n\n/** A dithering image filter with support for 4 dithering modes and multiple color palettes (2-color, 3-color, and multicolor options, using either predefined colors or ones sampled directly from the original image) */\nexport {\n imageDitheringFragmentShader,\n type ImageDitheringParams,\n type ImageDitheringUniforms,\n} from './shaders/image-dithering.js';\n\n/** Lens Distortion image filter that separates an image into shifting color layers, recreating the chromatic aberration of a lens, and warps the image geometry with barrel or pincushion curvature */\nexport {\n lensDistortionFragmentShader,\n lensDistortionMeta,\n type LensDistortionParams,\n type LensDistortionUniforms,\n} from './shaders/lens-distortion.js';\n\n/** A glowing gradient of colors flowing through an input image. The effect creates a smoothly animated wave of intensity across the image */\nexport {\n heatmapMeta,\n heatmapFragmentShader,\n toProcessedHeatmap,\n type HeatmapParams,\n type HeatmapUniforms,\n} from './shaders/heatmap.js';\n\n/** Futuristic liquid metal material applied to uploaded logo or one of pre-defined abstract shape */\nexport {\n liquidMetalFragmentShader,\n LiquidMetalShapes,\n toProcessedLiquidMetal,\n type LiquidMetalShape,\n type LiquidMetalParams,\n type LiquidMetalUniforms,\n} from './shaders/liquid-metal.js';\n\n/** A halftone-dot image filter featuring customizable grids, color palettes, and dot styles */\nexport {\n HalftoneDotsTypes,\n HalftoneDotsGrids,\n halftoneDotsFragmentShader,\n type HalftoneDotsParams,\n type HalftoneDotsUniforms,\n type HalftoneDotsType,\n type HalftoneDotsGrid,\n} from './shaders/halftone-dots.js';\n\n/** A halftone CMYK classic algo */\nexport {\n HalftoneCmykTypes,\n halftoneCmykFragmentShader,\n type HalftoneCmykParams,\n type HalftoneCmykUniforms,\n type HalftoneCmykType,\n} from './shaders/halftone-cmyk.js';\n\n/** Animated color fields running around a glassy logo shape */\nexport {\n gemSmokeMeta,\n gemSmokeFragmentShader,\n toProcessedGemSmoke,\n GemSmokeShapes,\n type GemSmokeShape,\n type GemSmokeParams,\n type GemSmokeUniforms,\n} from './shaders/gem-smoke.js';\n\n// ----- Utils ----- //\nexport { getShaderColorFromString } from './get-shader-color-from-string.js';\nexport { getShaderNoiseTexture } from './get-shader-noise-texture.js';\nexport { emptyPixel } from './empty-pixel.js';\n"],
5
- "mappings": ";;;;;AACA,SAAS,aAAa,4BAA4B;AAUlD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP,SAAS,gCAAgF;AAGzF;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP,SAAS,iCAAmF;AAG5F,SAAS,aAAa,6BAAuE;AAG7F,SAAS,2BAAiE;AAG1E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP,SAAS,aAAa,6BAAuE;AAG7F,SAAS,4BAAoE;AAG7E,SAAS,WAAW,2BAAiE;AAGrF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP,SAAS,2BAAiE;AAG1E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAGP;AAAA,EACE;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,kBAAkB;",
4
+ "sourcesContent": ["/** The core Shader Mount class. Pass it a parent element and a fragment shader to get started. */\nexport { ShaderMount, isPaperShaderElement } from './shader-mount.js';\nexport { isHtmlInCanvasSupported } from './html-in-canvas.js';\nexport { observeContentSize, type ShaderSizeToContent } from './size-to-content.js';\nexport type {\n PaperShaderElement,\n ShaderMotionParams,\n ShaderMountUniforms,\n ShaderPreset,\n ImageShaderPreset,\n} from './shader-mount.js';\n\n/** Shader sizing options and uniforms */\nexport {\n defaultObjectSizing,\n defaultPatternSizing,\n ShaderFitOptions,\n type ShaderFit,\n type ShaderSizingParams,\n type ShaderSizingUniforms,\n} from './shader-sizing.js';\n\n/** A flowing interplay of color spots, moving along distinct trajectories and transformed by organic distortion */\nexport {\n meshGradientFragmentShader,\n meshGradientMeta,\n type MeshGradientParams,\n type MeshGradientUniforms,\n} from './shaders/mesh-gradient.js';\n\n/** Radial multi-colored gradient shaped with layered noise for a natural, smoky aesthetic */\nexport {\n smokeRingMeta,\n smokeRingFragmentShader,\n type SmokeRingParams,\n type SmokeRingUniforms,\n} from './shaders/smoke-ring.js';\n\n/** A glowing, web-like structure of fluid lines and soft intersections. Great for creating atmospheric, organic-yet-futuristic visuals */\nexport { neuroNoiseFragmentShader, type NeuroNoiseParams, type NeuroNoiseUniforms } from './shaders/neuro-noise.js';\n\n/** Animated multi-color dots pattern with each dot orbiting around its cell center. Supports up to 40 colors and various shape and motion controls. Great for playful, dynamic backgrounds and UI textures */\nexport {\n dotOrbitMeta,\n dotOrbitFragmentShader,\n type DotOrbitParams,\n type DotOrbitUniforms,\n} from './shaders/dot-orbit.js';\n\n/** Static grid pattern made of circles, diamonds, squares or triangles */\nexport {\n dotGridFragmentShader,\n DotGridShapes,\n type DotGridShape,\n type DotGridParams,\n type DotGridUniforms,\n} from './shaders/dot-grid.js';\n\n/** A multi-color gradient mapped into smooth, animated curves, delivering a sleek, futuristic visual */\nexport {\n simplexNoiseMeta,\n simplexNoiseFragmentShader,\n type SimplexNoiseParams,\n type SimplexNoiseUniforms,\n} from './shaders/simplex-noise.js';\n\n/** Up to 20 gooey blobs moving around the center and merging into smooth organic shapes */\nexport {\n metaballsMeta,\n metaballsFragmentShader,\n type MetaballsParams,\n type MetaballsUniforms,\n} from './shaders/metaballs.js';\n\n/** Animated 3D Perlin noise with exposed controls */\nexport { perlinNoiseFragmentShader, type PerlinNoiseParams, type PerlinNoiseUniforms } from './shaders/perlin-noise.js';\n\n/** Anti-aliased animated Voronoi pattern with smooth and customizable edges */\nexport { voronoiMeta, voronoiFragmentShader, type VoronoiParams, type VoronoiUniforms } from './shaders/voronoi.js';\n\n/** Static line pattern configurable into textures ranging from sharp zigzags to smooth flowing waves */\nexport { wavesFragmentShader, type WavesParams, type WavesUniforms } from './shaders/waves.js';\n\n/** Animated color fields warped by noise and swirls, applied over base patterns (checks, stripes, or split edge). Blends up to 10 colors with adjustable distribution, softness, distortion, and swirl. Great for fluid, smoky, or marbled effects */\nexport {\n warpMeta,\n warpFragmentShader,\n WarpPatterns,\n type WarpParams,\n type WarpUniforms,\n type WarpPattern,\n} from './shaders/warp.js';\n\n/** Animated rays of light radiating from the center, blended with up to 5 colors. The rays are adjustable by size, density, brightness and center glow. Great for dramatic backgrounds, logo reveals, and VFX like energy bursts or sun shafts */\nexport { godRaysMeta, godRaysFragmentShader, type GodRaysParams, type GodRaysUniforms } from './shaders/god-rays.js';\n\n/** A single-colored animated spiral that morphs across a wide range of shapes - from crisp, thin-lined geometry to flowing whirlpool forms and wavy, abstract rings */\nexport { spiralFragmentShader, type SpiralParams, type SpiralUniforms } from './shaders/spiral.js';\n\n/** Animated bands of color twisting and bending, producing spirals, arcs, and flowing circular patterns */\nexport { swirlMeta, swirlFragmentShader, type SwirlParams, type SwirlUniforms } from './shaders/swirl.js';\n\n/** Animated 2-color dithering over with multiple pattern sources (noise, warp, dots, waves, ripple, swirl, sphere) */\nexport {\n ditheringFragmentShader,\n DitheringShapes,\n DitheringTypes,\n type DitheringParams,\n type DitheringUniforms,\n type DitheringShape,\n type DitheringType,\n} from './shaders/dithering.js';\n\n/** Multi-color gradients with grainy, noise-textured distortion available in 7 animated abstract forms */\nexport {\n grainGradientFragmentShader,\n grainGradientMeta,\n GrainGradientShapes,\n type GrainGradientParams,\n type GrainGradientUniforms,\n type GrainGradientShape,\n} from './shaders/grain-gradient.js';\n\n/** Luminous trails of color merging into a glowing gradient frame */\nexport {\n pulsingBorderMeta,\n pulsingBorderFragmentShader,\n PulsingBorderAspectRatios,\n type PulsingBorderParams,\n type PulsingBorderUniforms,\n type PulsingBorderAspectRatio,\n} from './shaders/pulsing-border.js';\n\n/** Glowing translucent 3D panels rotating around a central axis */\nexport {\n colorPanelsFragmentShader,\n colorPanelsMeta,\n type ColorPanelsParams,\n type ColorPanelsUniforms,\n} from './shaders/color-panels.js';\n\n/** Multi-point mesh gradients with up to 10 color spots, enhanced by two-direction warping, adjustable blend sharpness, and grain controls. Perfect for elegant wallpapers and atmospheric backdrops */\nexport {\n staticMeshGradientFragmentShader,\n staticMeshGradientMeta,\n type StaticMeshGradientParams,\n type StaticMeshGradientUniforms,\n} from './shaders/static-mesh-gradient.js';\n\n/** Radial gradient with up to 10 blended colors, featuring advanced focal point control, shape distortion, and grain effects */\nexport {\n staticRadialGradientFragmentShader,\n staticRadialGradientMeta,\n type StaticRadialGradientParams,\n type StaticRadialGradientUniforms,\n} from './shaders/static-radial-gradient.js';\n\n/** A static texture built from multiple noise layers, usable for a realistic paper and cardboard surfaces or generating abstract patterns. Can be used as a image filter or as a texture */\nexport {\n paperTextureFragmentShader,\n paperTextureMeta,\n type PaperTextureParams,\n type PaperTextureUniforms,\n} from './shaders/paper-texture.js';\n\n/** Water-like surface distortion with natural caustic realism. Works as an image filter or animated texture without image */\nexport { waterFragmentShader, type WaterParams, type WaterUniforms } from './shaders/water.js';\n\n/** Fluted glass image filter transforms an image into streaked, ribbed distortions, giving a mix of clarity and obscurity */\nexport {\n flutedGlassFragmentShader,\n GlassDistortionShapes,\n GlassGridShapes,\n type GlassDistortionShape,\n type GlassGridShape,\n type FlutedGlassParams,\n type FlutedGlassUniforms,\n} from './shaders/fluted-glass.js';\n\n/** A dithering image filter with support for 4 dithering modes and multiple color palettes (2-color, 3-color, and multicolor options, using either predefined colors or ones sampled directly from the original image) */\nexport {\n imageDitheringFragmentShader,\n type ImageDitheringParams,\n type ImageDitheringUniforms,\n} from './shaders/image-dithering.js';\n\n/** Lens Distortion image filter that separates an image into shifting color layers, recreating the chromatic aberration of a lens, and warps the image geometry with barrel or pincushion curvature */\nexport {\n lensDistortionFragmentShader,\n lensDistortionMeta,\n type LensDistortionParams,\n type LensDistortionUniforms,\n} from './shaders/lens-distortion.js';\n\n/** A glowing gradient of colors flowing through an input image. The effect creates a smoothly animated wave of intensity across the image */\nexport {\n heatmapMeta,\n heatmapFragmentShader,\n toProcessedHeatmap,\n type HeatmapParams,\n type HeatmapUniforms,\n} from './shaders/heatmap.js';\n\n/** Futuristic liquid metal material applied to uploaded logo or one of pre-defined abstract shape */\nexport {\n liquidMetalFragmentShader,\n LiquidMetalShapes,\n toProcessedLiquidMetal,\n type LiquidMetalShape,\n type LiquidMetalParams,\n type LiquidMetalUniforms,\n} from './shaders/liquid-metal.js';\n\n/** A halftone-dot image filter featuring customizable grids, color palettes, and dot styles */\nexport {\n HalftoneDotsTypes,\n HalftoneDotsGrids,\n halftoneDotsFragmentShader,\n type HalftoneDotsParams,\n type HalftoneDotsUniforms,\n type HalftoneDotsType,\n type HalftoneDotsGrid,\n} from './shaders/halftone-dots.js';\n\n/** A halftone CMYK classic algo */\nexport {\n HalftoneCmykTypes,\n halftoneCmykFragmentShader,\n type HalftoneCmykParams,\n type HalftoneCmykUniforms,\n type HalftoneCmykType,\n} from './shaders/halftone-cmyk.js';\n\n/** Animated color fields running around a glassy logo shape */\nexport {\n gemSmokeMeta,\n gemSmokeFragmentShader,\n toProcessedGemSmoke,\n GemSmokeShapes,\n type GemSmokeShape,\n type GemSmokeParams,\n type GemSmokeUniforms,\n} from './shaders/gem-smoke.js';\n\n// ----- Utils ----- //\nexport { getShaderColorFromString } from './get-shader-color-from-string.js';\nexport { getShaderNoiseTexture } from './get-shader-noise-texture.js';\nexport { emptyPixel } from './empty-pixel.js';\n"],
5
+ "mappings": ";;;;;AACA,SAAS,aAAa,4BAA4B;AAClD,SAAS,+BAA+B;AACxC,SAAS,0BAAoD;AAU7D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP,SAAS,gCAAgF;AAGzF;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP,SAAS,iCAAmF;AAG5F,SAAS,aAAa,6BAAuE;AAG7F,SAAS,2BAAiE;AAG1E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP,SAAS,aAAa,6BAAuE;AAG7F,SAAS,4BAAoE;AAG7E,SAAS,WAAW,2BAAiE;AAGrF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP,SAAS,2BAAiE;AAG1E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAGP;AAAA,EACE;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAGP,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,kBAAkB;",
6
6
  "names": []
7
7
  }
@@ -32,6 +32,8 @@ export declare class ShaderMount {
32
32
  private uniformCache;
33
33
  private textureUnitMap;
34
34
  private ownerDocument;
35
+ private htmlUniforms;
36
+ private isProvidedCanvas;
35
37
  constructor(
36
38
  /** The div you'd like to mount the shader to. The shader will match its size. */
37
39
  parentElement: HTMLElement, fragmentShader: string, uniforms: ShaderMountUniforms, webGlContextAttributes?: WebGLContextAttributes,
@@ -75,12 +77,23 @@ export declare class ShaderMount {
75
77
  private setupResizeObserver;
76
78
  private setupIntersectionObserver;
77
79
  private handleVisualViewportChange;
80
+ /** Resizes to the canvas right away, for size changes the resize observer would only see next frame */
81
+ syncSize: () => void;
78
82
  /** Resize handler for when the container div changes size or the max pixel count changes and we want to resize our canvas to match */
79
83
  private handleResize;
80
84
  private render;
81
85
  private requestRender;
82
86
  /** Creates a texture from an image and sets it into a uniform value */
83
87
  private setTextureUniform;
88
+ private createTexture;
89
+ /** Redraws the element, which has to be a child of the shader canvas, into the texture on every canvas paint */
90
+ private setHtmlUniform;
91
+ /** HTML is drawn 1:1, so its aspect ratio is the canvas aspect ratio */
92
+ private setHtmlAspectRatio;
93
+ private updateHtmlAspectRatios;
94
+ /** Captures each HTML uniform into its texture. On resize only HTML that has a snapshot already, so it can't throw */
95
+ private captureHtml;
96
+ private handleCanvasPaint;
84
97
  /** Utility: recursive equality test for all the uniforms */
85
98
  private areUniformValuesEqual;
86
99
  /** Sets the provided uniform values into the WebGL program, can be a partial list of uniforms that have changed */
@@ -100,6 +113,8 @@ export declare class ShaderMount {
100
113
  setMinPixelRatio: (newMinPixelRatio?: number) => void;
101
114
  /** Update the uniforms that are provided by the outside shader, can be a partial set with only the uniforms that have changed */
102
115
  setUniforms: (newUniforms: ShaderMountUniforms) => void;
116
+ /** Render right away only when the rAF loop isn't running */
117
+ private renderUnlessAnimating;
103
118
  private handleDocumentVisibilityChange;
104
119
  /** Dispose of the shader mount, cleaning up all of the WebGL resources */
105
120
  dispose: () => void;
@@ -117,7 +132,7 @@ export declare function isPaperShaderElement(element: HTMLElement): element is P
117
132
  * We just skip setting the uniform if it's undefined. This allows the shader mount to still take up space during server rendering
118
133
  */
119
134
  export interface ShaderMountUniforms {
120
- [key: string]: boolean | number | number[] | number[][] | HTMLImageElement | undefined;
135
+ [key: string]: boolean | number | number[] | number[][] | HTMLImageElement | HTMLElement | undefined;
121
136
  }
122
137
  export interface ShaderMotionParams {
123
138
  speed?: number;
@@ -4,6 +4,12 @@
4
4
  * * * * * * * * * * * * * * * * * * * * * * * * * * * */
5
5
 
6
6
  import { vertexShaderSource } from "./vertex-shader.js";
7
+ import {
8
+ drawHtml,
9
+ findDrawableCanvas,
10
+ isHtmlInCanvasSupported,
11
+ isHtmlUniform
12
+ } from "./html-in-canvas.js";
7
13
  const DEFAULT_MAX_PIXEL_COUNT = 1920 * 1080 * 4;
8
14
  class ShaderMount {
9
15
  parentElement;
@@ -39,6 +45,8 @@ class ShaderMount {
39
45
  uniformCache = {};
40
46
  textureUnitMap = /* @__PURE__ */ new Map();
41
47
  ownerDocument;
48
+ htmlUniforms = /* @__PURE__ */ new Map();
49
+ isProvidedCanvas = false;
42
50
  constructor(parentElement, fragmentShader, uniforms, webGlContextAttributes, speed = 0, frame = 0, minPixelRatio = 2, maxPixelCount = DEFAULT_MAX_PIXEL_COUNT, mipmaps = []) {
43
51
  if (parentElement?.nodeType === 1) {
44
52
  this.parentElement = parentElement;
@@ -52,20 +60,31 @@ class ShaderMount {
52
60
  styleElement.setAttribute("data-paper-shader", "");
53
61
  this.ownerDocument.head.prepend(styleElement);
54
62
  }
55
- const canvasElement = this.ownerDocument.createElement("canvas");
63
+ const providedCanvas = findDrawableCanvas(Object.values(uniforms), this.parentElement);
64
+ const canvasElement = providedCanvas ?? this.ownerDocument.createElement("canvas");
56
65
  this.canvasElement = canvasElement;
57
- this.parentElement.prepend(canvasElement);
66
+ this.isProvidedCanvas = providedCanvas !== null;
67
+ if (!providedCanvas) {
68
+ this.parentElement.prepend(canvasElement);
69
+ }
70
+ canvasElement.addEventListener("paint", this.handleCanvasPaint);
58
71
  this.fragmentShader = fragmentShader;
59
72
  this.providedUniforms = uniforms;
60
73
  this.mipmaps = mipmaps;
61
74
  this.currentFrame = frame;
62
75
  this.minPixelRatio = minPixelRatio;
63
76
  this.maxPixelCount = maxPixelCount;
64
- const gl = canvasElement.getContext("webgl2", webGlContextAttributes);
77
+ const gl = canvasElement.getContext("webgl2", {
78
+ antialias: false,
79
+ depth: false,
80
+ stencil: false,
81
+ ...webGlContextAttributes
82
+ });
65
83
  if (!gl) {
66
84
  throw new Error("Paper Shaders: WebGL is not supported in this browser");
67
85
  }
68
86
  this.gl = gl;
87
+ this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
69
88
  this.initProgram();
70
89
  this.setupPositionAttribute();
71
90
  this.setupUniforms();
@@ -82,6 +101,7 @@ class ShaderMount {
82
101
  const program = createProgram(this.gl, vertexShaderSource, this.fragmentShader);
83
102
  if (!program) return;
84
103
  this.program = program;
104
+ this.gl.useProgram(program);
85
105
  };
86
106
  setupPositionAttribute = () => {
87
107
  const positionAttributeLocation = this.gl.getAttribLocation(this.program, "a_position");
@@ -100,9 +120,10 @@ class ShaderMount {
100
120
  };
101
121
  Object.entries(this.providedUniforms).forEach(([key, value]) => {
102
122
  uniformLocations[key] = this.gl.getUniformLocation(this.program, key);
103
- if (value instanceof HTMLImageElement) {
123
+ if (value instanceof HTMLImageElement || isHtmlUniform(value)) {
104
124
  const aspectRatioUniformName = `${key}AspectRatio`;
105
125
  uniformLocations[aspectRatioUniformName] = this.gl.getUniformLocation(this.program, aspectRatioUniformName);
126
+ uniformLocations[`${key}IsHtml`] = this.gl.getUniformLocation(this.program, `${key}IsHtml`);
106
127
  }
107
128
  });
108
129
  this.uniformLocations = uniformLocations;
@@ -136,7 +157,7 @@ class ShaderMount {
136
157
  }
137
158
  this.handleResize();
138
159
  });
139
- this.resizeObserver.observe(this.parentElement);
160
+ this.resizeObserver.observe(this.canvasElement);
140
161
  };
141
162
  setupIntersectionObserver = () => {
142
163
  const view = this.ownerDocument.defaultView;
@@ -157,6 +178,17 @@ class ShaderMount {
157
178
  this.resizeObserver?.disconnect();
158
179
  this.setupResizeObserver();
159
180
  };
181
+ /** Resizes to the canvas right away, for size changes the resize observer would only see next frame */
182
+ syncSize = () => {
183
+ const style = getComputedStyle(this.canvasElement);
184
+ this.parentWidth = parseFloat(style.width) || 0;
185
+ this.parentHeight = parseFloat(style.height) || 0;
186
+ if (this.devicePixelsSupported) {
187
+ this.parentDevicePixelWidth = Math.round(this.parentWidth * window.devicePixelRatio);
188
+ this.parentDevicePixelHeight = Math.round(this.parentHeight * window.devicePixelRatio);
189
+ }
190
+ this.handleResize();
191
+ };
160
192
  /** Resize handler for when the container div changes size or the max pixel count changes and we want to resize our canvas to match */
161
193
  handleResize = () => {
162
194
  let targetPixelWidth = 0;
@@ -187,6 +219,11 @@ class ShaderMount {
187
219
  this.canvasElement.height = newHeight;
188
220
  this.resolutionChanged = true;
189
221
  this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
222
+ this.updateHtmlAspectRatios();
223
+ this.captureHtml(true);
224
+ if (this.htmlUniforms.size > 0) {
225
+ this.canvasElement.requestPaint();
226
+ }
190
227
  this.render(performance.now());
191
228
  }
192
229
  };
@@ -202,7 +239,6 @@ class ShaderMount {
202
239
  this.currentFrame += dt * this.currentSpeed;
203
240
  }
204
241
  this.gl.clear(this.gl.COLOR_BUFFER_BIT);
205
- this.gl.useProgram(this.program);
206
242
  this.gl.uniform1f(this.uniformLocations.u_time, this.currentFrame * 1e-3);
207
243
  if (this.resolutionChanged) {
208
244
  this.gl.uniform2f(this.uniformLocations.u_resolution, this.gl.canvas.width, this.gl.canvas.height);
@@ -227,21 +263,8 @@ class ShaderMount {
227
263
  if (!image.complete || image.naturalWidth === 0) {
228
264
  throw new Error(`Paper Shaders: image for uniform ${uniformName} must be fully loaded`);
229
265
  }
230
- const existingTexture = this.textures.get(uniformName);
231
- if (existingTexture) {
232
- this.gl.deleteTexture(existingTexture);
233
- }
234
- if (!this.textureUnitMap.has(uniformName)) {
235
- this.textureUnitMap.set(uniformName, this.textureUnitMap.size);
236
- }
237
- const textureUnit = this.textureUnitMap.get(uniformName);
238
- this.gl.activeTexture(this.gl.TEXTURE0 + textureUnit);
239
- const texture = this.gl.createTexture();
240
- this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
241
- this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
242
- this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
243
- this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
244
- this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
266
+ this.htmlUniforms.delete(uniformName);
267
+ const { texture, textureUnit } = this.createTexture(uniformName);
245
268
  this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, image);
246
269
  if (this.mipmaps.includes(uniformName)) {
247
270
  this.gl.generateMipmap(this.gl.TEXTURE_2D);
@@ -262,8 +285,80 @@ class ShaderMount {
262
285
  const aspectRatio = image.naturalWidth / image.naturalHeight;
263
286
  this.gl.uniform1f(aspectRatioLocation, aspectRatio);
264
287
  }
288
+ this.gl.uniform1f(this.uniformLocations[`${uniformName}IsHtml`] ?? null, 0);
289
+ }
290
+ };
291
+ createTexture = (uniformName) => {
292
+ const existingTexture = this.textures.get(uniformName);
293
+ if (existingTexture) {
294
+ this.gl.deleteTexture(existingTexture);
295
+ }
296
+ if (!this.textureUnitMap.has(uniformName)) {
297
+ this.textureUnitMap.set(uniformName, this.textureUnitMap.size);
298
+ }
299
+ const textureUnit = this.textureUnitMap.get(uniformName);
300
+ this.gl.activeTexture(this.gl.TEXTURE0 + textureUnit);
301
+ const texture = this.gl.createTexture();
302
+ this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
303
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
304
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
305
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
306
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
307
+ return { texture, textureUnit };
308
+ };
309
+ /** Redraws the element, which has to be a child of the shader canvas, into the texture on every canvas paint */
310
+ setHtmlUniform = (uniformName, element) => {
311
+ this.htmlUniforms.delete(uniformName);
312
+ const { texture, textureUnit } = this.createTexture(uniformName);
313
+ if (texture === null) return;
314
+ this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, 1, 1, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null);
315
+ this.textures.set(uniformName, texture);
316
+ this.gl.uniform1i(this.uniformLocations[uniformName] ?? null, textureUnit);
317
+ this.gl.uniform1f(this.uniformLocations[`${uniformName}IsHtml`] ?? null, 1);
318
+ this.setHtmlAspectRatio(uniformName);
319
+ if (!isHtmlInCanvasSupported()) {
320
+ console.warn(`Paper Shaders: HTML for ${uniformName} needs HTML in canvas support`);
321
+ return;
322
+ }
323
+ if (element.parentElement !== this.canvasElement) {
324
+ console.warn(`Paper Shaders: HTML for ${uniformName} has to be a child of the shader canvas`);
325
+ return;
326
+ }
327
+ this.htmlUniforms.set(uniformName, { element });
328
+ this.canvasElement.requestPaint();
329
+ };
330
+ /** HTML is drawn 1:1, so its aspect ratio is the canvas aspect ratio */
331
+ setHtmlAspectRatio = (uniformName) => {
332
+ this.gl.uniform1f(
333
+ this.uniformLocations[`${uniformName}AspectRatio`] ?? null,
334
+ this.gl.canvas.width / this.gl.canvas.height
335
+ );
336
+ };
337
+ updateHtmlAspectRatios = () => {
338
+ for (const [uniformName, value] of Object.entries(this.providedUniforms)) {
339
+ if (isHtmlUniform(value)) {
340
+ this.setHtmlAspectRatio(uniformName);
341
+ }
265
342
  }
266
343
  };
344
+ /** Captures each HTML uniform into its texture. On resize only HTML that has a snapshot already, so it can't throw */
345
+ captureHtml = (isResize) => {
346
+ const canvas = this.canvasElement;
347
+ this.htmlUniforms.forEach((html, uniformName) => {
348
+ if (isResize && html.layout === void 0) return;
349
+ this.gl.activeTexture(this.gl.TEXTURE0 + this.textureUnitMap.get(uniformName));
350
+ this.gl.bindTexture(this.gl.TEXTURE_2D, this.textures.get(uniformName));
351
+ const isFirstCapture = html.layout === void 0;
352
+ html.layout = drawHtml(this.gl, canvas, html.element, html.layout);
353
+ if (isFirstCapture) {
354
+ canvas.updateElementGeometry(html.element, { canvasTransform: new DOMMatrix() });
355
+ }
356
+ });
357
+ };
358
+ handleCanvasPaint = () => {
359
+ this.captureHtml(false);
360
+ this.renderUnlessAnimating();
361
+ };
267
362
  /** Utility: recursive equality test for all the uniforms */
268
363
  areUniformValuesEqual = (a, b) => {
269
364
  if (a === b) return true;
@@ -274,7 +369,6 @@ class ShaderMount {
274
369
  };
275
370
  /** Sets the provided uniform values into the WebGL program, can be a partial list of uniforms that have changed */
276
371
  setUniformValues = (updatedUniforms) => {
277
- this.gl.useProgram(this.program);
278
372
  Object.entries(updatedUniforms).forEach(([key, value]) => {
279
373
  let cacheValue = value;
280
374
  if (value instanceof HTMLImageElement) {
@@ -289,6 +383,8 @@ class ShaderMount {
289
383
  }
290
384
  if (value instanceof HTMLImageElement) {
291
385
  this.setTextureUniform(key, value);
386
+ } else if (isHtmlUniform(value)) {
387
+ this.setHtmlUniform(key, value);
292
388
  } else if (Array.isArray(value)) {
293
389
  let flatArray = null;
294
390
  let valueLength = null;
@@ -341,7 +437,7 @@ class ShaderMount {
341
437
  setFrame = (newFrame) => {
342
438
  this.currentFrame = newFrame;
343
439
  this.lastRenderTime = performance.now();
344
- this.render(performance.now());
440
+ this.renderUnlessAnimating();
345
441
  };
346
442
  /** Set an animation speed (or 0 to stop animation) */
347
443
  setSpeed = (newSpeed = 1) => {
@@ -377,7 +473,13 @@ class ShaderMount {
377
473
  setUniforms = (newUniforms) => {
378
474
  this.setUniformValues(newUniforms);
379
475
  this.providedUniforms = { ...this.providedUniforms, ...newUniforms };
380
- this.render(performance.now());
476
+ this.renderUnlessAnimating();
477
+ };
478
+ /** Render right away only when the rAF loop isn't running */
479
+ renderUnlessAnimating = () => {
480
+ if (this.rafId === null) {
481
+ this.render(performance.now());
482
+ }
381
483
  };
382
484
  handleDocumentVisibilityChange = () => {
383
485
  this.updateCurrentSpeed();
@@ -389,6 +491,8 @@ class ShaderMount {
389
491
  cancelAnimationFrame(this.rafId);
390
492
  this.rafId = null;
391
493
  }
494
+ this.canvasElement.removeEventListener("paint", this.handleCanvasPaint);
495
+ this.htmlUniforms.clear();
392
496
  if (this.gl && this.program) {
393
497
  this.textures.forEach((texture) => {
394
498
  this.gl.deleteTexture(texture);
@@ -402,6 +506,9 @@ class ShaderMount {
402
506
  this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);
403
507
  this.gl.getError();
404
508
  }
509
+ if (!this.isProvidedCanvas) {
510
+ this.gl.getExtension("WEBGL_lose_context")?.loseContext();
511
+ }
405
512
  if (this.resizeObserver) {
406
513
  this.resizeObserver.disconnect();
407
514
  this.resizeObserver = null;
@@ -413,7 +520,9 @@ class ShaderMount {
413
520
  visualViewport?.removeEventListener("resize", this.handleVisualViewportChange);
414
521
  this.ownerDocument.removeEventListener("visibilitychange", this.handleDocumentVisibilityChange);
415
522
  this.uniformLocations = {};
416
- this.canvasElement.remove();
523
+ if (!this.isProvidedCanvas) {
524
+ this.canvasElement.remove();
525
+ }
417
526
  delete this.parentElement.paperShaderMount;
418
527
  };
419
528
  }
@@ -462,7 +571,7 @@ const defaultStyle = `@layer paper-shaders {
462
571
  isolation: isolate;
463
572
  position: relative;
464
573
 
465
- & canvas {
574
+ & > canvas {
466
575
  contain: strict;
467
576
  display: block;
468
577
  position: absolute;
@@ -473,6 +582,14 @@ const defaultStyle = `@layer paper-shaders {
473
582
  border-radius: inherit;
474
583
  corner-shape: inherit;
475
584
  }
585
+
586
+ & > canvas > [drawable],
587
+ & > [drawable] {
588
+ box-sizing: border-box;
589
+ position: relative;
590
+ width: 100%;
591
+ height: 100%;
592
+ }
476
593
  }
477
594
  }`;
478
595
  function isPaperShaderElement(element) {