SVG with Normalized Coordinates
This post demonstrates how to generate SVG content with JavaScript using normalized coordinates (-1 to 1) similar to fragment shaders.
Key Concepts
Normalized Coordinates
// Convert screen position to normalized coordinates (-1 to 1)
const nx = (i / resolution) * 2 - 1;
const ny = (j / resolution) * 2 - 1;
// Convert normalized coordinates back to SVG coordinates
function normToSvg(nx, ny, width, height) {
const x = (nx + 1) * width * 0.5;
const y = (-ny + 1) * height * 0.5; // Flip Y for SVG
return { x, y };
}
Fragment Shader-like Functions
function fragmentShader(nx, ny, time) {
const dist = length(nx, ny);
const angle = Math.atan2(ny, nx);
const rings = sin(dist * 10 - time * 2) * 0.5 + 0.5;
const spiral = sin(angle * 8 + dist * 20 - time * 3) * 0.5 + 0.5;
return { r: rings, g: spiral, b: 0.8 };
}
Performance Considerations
- Resolution: Lower resolution = better performance
- Animation: Use
requestAnimationFrame
for smooth animation - Batch Operations: Create all elements before adding to DOM
- Consider Canvas: For very high-resolution patterns, HTML5 Canvas might be more efficient
Advanced Techniques
- Use viewBox: Define custom coordinate systems
- Float Precision: JavaScript numbers are 64-bit floats, perfect for shader-like calculations
- Color Spaces: Convert between HSL, RGB, and normalized color values
- Time-based Animation: Use timestamps for consistent animation speed
- Interactive: Add mouse/touch events for interactive experiences
This approach gives you the flexibility of fragment shaders with the scalability and styling capabilities of SVG!