Lightning

by sosegon

HTML

<svg id="scene" width="500" height="500" style="background:black;">
    <polyline id="lightning" stroke="white" stroke-width="2" fill="none" filter="url(#glow)" />
    
    <defs>
        <filter id="glow">
            <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
            <feMerge>
                <feMergeNode in="coloredBlur"/>
                <feMergeNode in="SourceGraphic"/>
            </feMerge>
        </filter>
    </defs>
</svg>

<script>
    function generateLightning(startX, startY, endX, endY, segments = 10) {
        let points = [{ x: startX, y: startY }];
        
        for (let i = 1; i <= segments; i++) {
            let x = startX + (Math.random() * 40 - 20);  // Random horizontal offset
            let y = startY + ((endY - startY) / segments) * i;
            points.push({ x, y });
        }

        points.push({ x: endX, y: endY });

        return points;
    }

    function drawLightning() {
        const svg = document.getElementById("scene");
        const lightning = document.getElementById("lightning");

        // Random start and end points
        let startX = Math.random() * 500;
        let startY = 0;
        let endX = startX + (Math.random() * 40 - 20);
        let endY = 500;

        let points = generateLightning(startX, startY, endX, endY, 20);
        lightning.setAttribute("points", points.map(p => `${p.x},${p.y}`).join(" "));

        // Flicker effect
        lightning.style.opacity = 1;
        setTimeout(() => lightning.style.opacity = 0, 100);
    }

    // Generate lightning every second
    setInterval(drawLightning, 1000);
</script>