Search code examples
javascriptsvg

Is it possible to invert the clipping of SVG?


I have a rectangle on an SVG element. I then want to draw another rectangle over the whole SVG area except the rect I've already drawn.

I thought masks might be a solution but they seem to act just like clipping - doing the inverse of what I want. I've tried this:

<svg id="mySVG" width="600" height="250">
    <defs>
        <mask id="myMask" x="0" y="0" width="600" height="250" >
            <circle cx="25" cy="25" r="25" fill="white"/>
        </mask>
    </defs>

    <rect x="0" y="0" width="600" height="250" fill="red" mask="url(#myMask)"></rect>
</svg>

So what I'm after is the inverse of this image.


Solution

  • Draw a rect for the whole thing then use a black circle to cut out the whole.

    Or alternatively and more performantly, draw the whole thing with a path wherein you can draw the rect clockwise and the circle anticlockwise as a cut-out.

    Here's the easiest first option given that you are already most of the way there with that one.

     <svg id="mySVG" width="600" height="250">
        <defs>
            <mask id="myMask" x="0" y="0" width="600" height="250" >
                <rect width="600" height="250" fill="white"/>
                <circle cx="25" cy="25" r="25" fill="black"/>
            </mask>
        </defs>
    
        <rect x="0" y="0" width="600" height="250" fill="red" mask="url(#myMask)"></rect>
    </svg>