Theta Nil's Site

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

Advanced Techniques

  1. Use viewBox: Define custom coordinate systems
  2. Float Precision: JavaScript numbers are 64-bit floats, perfect for shader-like calculations
  3. Color Spaces: Convert between HSL, RGB, and normalized color values
  4. Time-based Animation: Use timestamps for consistent animation speed
  5. 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!

Tags: