Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut a hole in an SVG rectangle [duplicate]

Tags:

svg

So basically as my title says, I want to "cut a hole" in a rect element.

I have two rect elements, one on top of the other. The one on the bottom has a fill colour of white, and the one on the top has a fill colour of grey.

What I want to do is cut a triangle out of the top rect element so that the rect element below shows through.

This svg element is going to be used as an audio button for a media player on a page. In other words, you'll be able to click (or drag) your mouse left/right and the change in audio level will be represented by a change in the width of the rect element on the bottom, which shows through the triangle cut out of the top rect element.

I hope that's not too confusing. :P

Here is a quick mockup of what it should look like: http://forboden.com/coding/s1.png

Here is my code: http://forboden.com/coding/svgClipTest.html

Where am I going wrong here?

like image 773
Yansky Avatar asked Sep 18 '10 16:09

Yansky


People also ask

How do I delete part of an SVG?

In order to remove SVG content, you can use the remove() function provided by D3. js.

How does SVG path work?

The <path> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more. Paths create complex shapes by combining multiple straight lines or curved lines. Complex shapes composed only of straight lines can be created as <polyline> s.


1 Answers

You should be able to use the fill-rule: evenodd(default) 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:

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

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:

enter image description here

like image 110
cuixiping Avatar answered Sep 20 '22 08:09

cuixiping