JSFiddle - React, Tailwind, and code Playground

by Pankaj Kargirwar

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Global SVG Clipping</title>
</head>
<body>
    <svg id="my-svg" width="400" height="300" style="border: 1px solid black">
        <!-- Some sample SVG elements -->
        <circle cx="200" cy="150" r="100" fill="blue"></circle>
        <rect x="50" y="50" width="300" height="200" fill="red" opacity="0.5"></rect>
        <text x="50" y="50" font-size="30" fill="white">Clipping Example</text>
    </svg>

    <script>
        // Select the SVG element
        const svg = document.getElementById('my-svg');

        // Create a <defs> section if it doesn't exist
        let defs = svg.querySelector('defs');
        if (!defs) {
            defs = document.createElementNS("http://www.w3.org/2000/svg", "defs");
            svg.appendChild(defs);
        }

        // Create a <clipPath> element
        const clipPath = document.createElementNS("http://www.w3.org/2000/svg", "clipPath");
        clipPath.setAttribute("id", "global-clip");

        // Define the clipping rectangle
        const clipRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
        clipRect.setAttribute("x", "0");
        clipRect.setAttribute("y", "0");
        clipRect.setAttribute("width", "400");
        clipRect.setAttribute("height", "300");
        clipPath.appendChild(clipRect);

        // Add the <clipPath> to <defs>
        defs.appendChild(clipPath);

        // Apply the clipPath to all elements within the SVG
        Array.from(svg.children).forEach((child) => {
            if (child.tagName !== 'defs') {
                child.setAttribute("clip-path", "url(#global-clip)");
            }
        });
    </script>
</body>
</html>