Shader Web Background Toolkit
Built with shader-web-background by xemantic • Claude • cursor.com
A complete development environment for creating WebGL shader backgrounds. This project includes AI-assisted Shadertoy conversion rules, a shader registry system, and example implementations ranging from simple gradients to complex raymarched fractals.
π Examples:
- Minimal Example β Clean, self-contained integration example
- Viewport-Aware Example β Performance-optimized rendering with IntersectionObserver API
- Shader Borders β Multi-canvas showcase with animated shader borders on cards
GitHub Repository: https://github.com/MRKNSTUDIO/shader-background
π― What This Project Does
This toolkit solves the common problem of porting Shadertoy shaders to production websites. While Shadertoy uses WebGL 2.0 features, most production sites need WebGL 1.0 compatibility. This project provides:
- AI Conversion Rules: Comprehensive
.cursorrules that teach any AI assistant how to convert Shadertoy code automatically - Shader Registry: A clean JavaScript API for registering and switching between multiple shaders
- Working Examples: From simple gradients to complex multi-pass feedback loops
- Interaction Handling: Mouse, scroll parallax, and device orientation support
- Error Handling: Built-in
onErrorcallback for graceful fallbacks when WebGL is unavailable
π Project Structure
/shader-background/
βββ .cursor/
β βββ rules/
β βββ converting-from-shadertoy.mdc β AI conversion rules
β βββ css-styling.mdc β CSS styling guidelines
β βββ interaction.mdc β Mouse/gyro handling
β βββ shader-testing-environment.mdc β Project documentation
βββ src/
β βββ shader-web-background.min.js β Core library
β βββ main.js β ShaderRegistry controller
β βββ styles.css β UI styling
βββ shaders/
β βββ gradient.js β Simple single-pass
β βββ feedback-circle.js β Two-pass with buffer
β βββ spectral-feedback.js β Zucconi spectral colors
β βββ interactive-blob.js β Mouse/gyro interaction
β βββ demo-shader.js β Advanced multi-input
β βββ voronoi-dreams.js β Ethereal flowing ribbons
β βββ shadertoy-example-*.js β Converted Shadertoy shaders
βββ shadertoy/
β βββ shadertoy-example-*.txt β Original Shadertoy source code
βββ examples/
β βββ minimal-example.html β Minimal integration example
β βββ viewport-aware-example.html β Performance-optimized example
β βββ card-borders-experiment.html β Shader borders on cards
βββ index.html β Main demo (shader source + UI)
βββ README.md β Project documentation
βββ favicon.ico β Site icon
π€ AI Conversion Rules
The .cursor/rules/converting-from-shadertoy.mdc file contains comprehensive conversion
instructions for AI assistants. When working with Shadertoy code, the AI will automatically:
- Convert
mainImage()βmain()entry point - Replace
fragCoord/fragColorwith GLSL equivalents - Fix
iResolutiontype mismatch (vec3 β vec2) - Rewrite complex for-loops to WebGL 1.0 compatible form
- Implement missing functions like
tanh(),isnan(),round() - Expand problematic macros and fix variable shadowing
- Convert
texture()βtexture2D()
π‘ Using the Rules in Cursor
Cursor IDE automatically detects the .cursor/rules/ folder. When you paste Shadertoy code and ask
the AI to convert it, the rules are applied automatically.
// Just ask:
"Convert this Shadertoy shader to work with shader-web-background"
// The AI will apply all 10 conversion steps:
// 1. Entry point conversion
// 2. iResolution type fix
// 3. For loop restrictions
// 4. Missing function implementations
// 5. Variable declaration cleanup
// 6. Macro expansion
// 7. Name conflict resolution
// 8. Boolean/float type mixing
// 9. Multi-pass buffer setup
// 10. Texture sampling syntax
π§ Using Rules in Other IDEs
Not using Cursor? Copy the rules to your AI-enabled IDE:
- VS Code + Copilot/Codeium: Create
.github/copilot-instructions.mdand paste the rule contents - JetBrains + AI Assistant: Add to project-level AI context or custom prompts
- Windsurf: Use
.windsurfrulesfile in project root - Any AI Chat: Paste the rules as system context before your conversion request
The rules are written as general GLSL conversion instructionsβthey work with any AI model that understands code.
π Adding Your Own Shaders
Step 1: Add shader source to index.html
<script type="x-shader/x-fragment" id="my-shader-image">
precision highp float;
uniform float iTime;
uniform vec2 iResolution;
void main() {
vec2 uv = gl_FragCoord.xy / iResolution;
vec3 col = 0.5 + 0.5 * cos(iTime + uv.xyx + vec3(0, 2, 4));
gl_FragColor = vec4(col, 1.0);
}
</script>
Step 2: Create registration file shaders/my-shader.js
ShaderRegistry.register('my-shader', {
onError: function (error, canvas) {
// Optional: Handle errors (e.g., WebGL not supported)
console.error('Shader failed:', error);
},
shaders: {
'my-shader-image': {
uniforms: {
iTime: (gl, loc) => gl.uniform1f(loc, performance.now() / 1000),
iResolution: (gl, loc, ctx) => gl.uniform2f(loc, ctx.width, ctx.height)
}
}
}
}, '<strong>My Shader</strong> Custom description here.');
Step 3: Add dropdown option and script include in index.html
<option value="my-shader">My Shader</option>
<script src="shaders/my-shader.js"></script>
π Multi-Pass Shaders (Feedback Buffers)
For shaders that need previous frame data (trails, blur, reaction-diffusion), use a two-pass setup:
// Buffer pass: reads from itself, writes processed result
'my-shader-buffer': {
uniforms: {
iChannel0: (gl, loc, ctx) => ctx.texture(loc, ctx.buffers['my-shader-buffer']),
iResolution: (gl, loc, ctx) => gl.uniform2f(loc, ctx.width, ctx.height)
}
}
// Image pass: reads buffer and outputs to screen
'my-shader-image': {
uniforms: {
iChannel0: (gl, loc, ctx) => ctx.texture(loc, ctx.buffers['my-shader-buffer']),
iResolution: (gl, loc, ctx) => gl.uniform2f(loc, ctx.width, ctx.height)
}
}
The library handles double-buffering automaticallyβyou read from the previous frame and write to the current frame.
π±οΈ Mouse & Gyro Interaction
The library provides coordinate conversion helpers. Handle events in your application code:
// Track mouse position
let mouseX = 0, mouseY = 0;
document.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
// Convert in onBeforeFrame callback
onBeforeFrame: (ctx) => {
shaderMouseX = ctx.toShaderX(mouseX);
shaderMouseY = ctx.toShaderY(mouseY);
}
// Pass as uniforms
uniforms: {
iMouse: (gl, loc) => gl.uniform2f(loc, shaderMouseX, shaderMouseY)
}
Device orientation uses the same pattern with deviceorientation events and
beta/gamma values.
β οΈ Error Handling
The shader-web-background library provides an onError callback that is called when
shader initialization fails (e.g., WebGL not supported, missing capabilities). Use this to handle errors
gracefully:
shaderWebBackground.shade({
onError: function (error, canvas) {
// Create fallback UI element only when needed
const notification = document.createElement('div');
notification.className = 'webgl-notification';
notification.textContent = 'β οΈ Shader cannot be played on this device';
document.body.appendChild(notification);
console.error('Shader initialization failed:', error);
},
shaders: { /* ... */ }
});
Best Practice: Don't create fallback elements in the DOM upfront. Instead, create them
dynamically in the onError callback only when the shader cannot be displayed. This keeps your HTML
clean and avoids unnecessary DOM elements for users with WebGL support.
The library automatically detects WebGL support and capabilities, so you don't need to manually check for WebGL
availability before calling shade().
β‘ Quick Shadertoy Conversion Checklist
- Add
precision highp float;at top - Declare uniforms:
iTime,iResolution,iChannel0... mainImage(out vec4 fragColor, vec2 fragCoord)βvoid main()fragCoordβgl_FragCoord.xyfragColorβgl_FragColorvec3 r = iResolutionβvec3 r = vec3(iResolution, 1.0)- Complex for-loops β simple
for(int i=0; i<N; i++)with break tanh(x)β custom implementationisnan(x)βx != xtexture()βtexture2D()
π¨ Included Shader Examples
Use the dropdown at the top to switch between shaders:
- Simple Gradient: Single-pass animated color cycling using sin waves
- Feedback Circle: Orbiting circle with fading trailβdemonstrates buffer feedback
- Spectral Feedback: Zucconi spectral algorithm for natural rainbow colors
- Interactive Blob: Mouse and gyroscope controlled metaballs with trails
- Demo Shader: Advanced multi-input: mouse, scroll parallax, device orientation
- Shadertoy Examples 1-3: Real-world Shadertoy ports demonstrating conversion techniques
π Resources
- shader-web-background GitHub β Original library by xemantic
- Shadertoy β Shader community and inspiration
- The Book of Shaders β Learn GLSL fundamentals
- Inigo Quilez Articles β Advanced shader techniques
π Getting Started
- Download or clone this repository from GitHub
- Open
index.htmlin a browser (use a local server for best results) - Use the dropdown to switch between shader examples
- Copy any shader as a template for your own creations
- Paste Shadertoy code and let AI handle the conversion using the included rules
Made with β€οΈ for the shader community