How can I cut one shape inside another?

前端 未结 4 1272
北恋
北恋 2020-11-30 01:31

Is there a way to cut one shape out of another in SVG? For example, I have a rect and an ellipse and I want to make a rect with a transparent hole in the middle. I would i

相关标签:
4条回答
  • 2020-11-30 02:14

    Unfortunately it seems that there's no way to do this. Neither SVG 1.0 nor SVG 1.1 do not support boolean shape operations, clipping is supported for other reasons. The closest you can get is trying to get a "inverted" shape to do the clipping.

    0 讨论(0)
  • 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:

    0 讨论(0)
  • 2020-11-30 02:22

    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)

    <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:

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

    0 讨论(0)
  • 2020-11-30 02:23

    You need to use a <path> if you want to use fill-rule. But it's certainly possible to change the radius of a circle that is a subpath of the <path>, you just need to master the arc path command.

    0 讨论(0)
提交回复
热议问题