How can I cut one shape inside another?

You should be able to use the fill-rule: evenodd property to achieve this effect, if you want to prevent the fill of the rectangle from painting where the circle is. See this example from the SVG specification (image below will only display if your browser supports SVG):

A pentagram and two circles, filled in red, with the centers cut showing the white background

For some reason, I can't seem to get this to work with shapes like the rect and ellipse that you provided in the question. Here's my attempt:

A blue square with a circle inside


You must use path element to cut a hole.

See the example from the SVG specification: (you can click this link or the following image to view the real svg file)

svg hole example

<g fill-rule="evenodd" fill="red" stroke="black" stroke-width="3">
    <path d="M 250,75 L 323,301 131,161 369,161 177,301 z"/>

    <path d="M 600,81 A 107,107 0 0,1 600,295 A 107,107 0 0,1 600,81 z
             M 600,139 A 49,49 0 0,1 600,237 A 49,49 0 0,1 600,139 z"/>

    <path d="M 950,81 A 107,107 0 0,1 950,295 A 107,107 0 0,1 950,81 z
             M 950,139 A 49,49 0 0,0 950,237 A 49,49 0 0,0 950,139 z"/>
</g>

For your case:

<path d="M10 10h50v50h-50z M23 35a14 10 0 1 1 0 0.0001 z"
    stroke="blue" stroke-width="2" fill="red" fill-rule="evenodd" />

M10 10h50v50h-50z will draw a rect.

M25 35a10 10 0 1 1 0 0.0001 z will draw a ellipse.

fill-rule="evenodd" will make the hole.


The key point is draw outer shape and inner shapes(holes) in different direction (clockwise vs anti-clockwise).

  • Draw the outer shape clockwise and draw the inner(holes) shapes anti-clockwise.
  • Or conversely, draw the outer shape(holes) anti-clockwise and draw the inner shapes clockwise.
  • Concat the path datas of outer shape and inner shapes(holes).

You can cut more holes by concat more hole path data.

This image explain how to cut a hole:

This image explain how to cut a hole

See w3c docs: SVG Arc Commands and SVG fill-rule Property.

Tags:

Svg