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>Dynamic SVG Clipping</title>
</head>
<body>
    <svg id="my-svg" width="400" height="300" style="border: 1px solid black">
        <!-- Defs for clipping path -->
        <defs>
            <clipPath id="global-clip">
                <rect x="50" y="50" width="300" height="200"></rect>
            </clipPath>
        </defs>

        <!-- Elements -->
        <circle cx="200" cy="150" r="100" fill="blue" clip-path="url(#global-clip)"></circle>
        <rect x="100" y="100" width="200" height="100" fill="red" clip-path="url(#global-clip)" opacity="0.5"></rect>
    </svg>

    <button id="update-clip">Update Clip Path</button>

    <script>
        // Update the clip path dynamically
        document.getElementById('update-clip').addEventListener('click', () => {
            const clipRect = document.querySelector('#global-clip rect');
            clipRect.setAttribute('x', '100');
            clipRect.setAttribute('y', '100');
            clipRect.setAttribute('width', '200');
            clipRect.setAttribute('height', '100');
        });
    </script>
</body>
</html>