HiveBrain v1.2.0
Get Started
← Back to all entries
patternhtmlMinor

Cutting rectangle from circle

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rectanglecirclefromcutting

Problem

Can the following code snippet be optimized or am I doing it right?



http://jsfiddle.net/5z4npr5L/6/

I don't want to use a path because I want it readable.

Solution

While I don't entirely agree with not using path, I will try to keep my answer unbiased. This is because using a path is much more developer-friendly, and opens up more options to do what you ask.

Keep your code styled, with--that's right--tabs

Using tabs in your code to indent it makes it a lot more readable and allows you to see the structure much more easily. You can see the difference in the following two code examples:

Before:



After:


    
        
        
    
    


XMLNS isn't needed

Unless you're using XHTML, XML, or any other kind of page that requires an XML parser, then XMLNS is not needed. Since inline SVG is a recent development in HTML5, this is never really needed. I'm also going to add that you added the tags HTML and CSS to this, so I'll assume you don't want XMLNS.

Your final code should look something like this:













There isn't much more you could optimize without using path. Using path would allow you to use things like fill-rule="evenodd", and many other options.

EDIT:

@somethinghere asked me to expound a bit on how to use the extra features available with path that would allow you to do shape cutouts much more easily.

  • fill-rule="evenodd"



This can be used on a ` element and have the element have multiple shapes, if the shape number is even in the path call, it will define an outside point. If it's odd, it'll define an inside point. This allows you to define two path segments, your circle and your rectangle, and have the rect mark the inside point. This is an implementation using fill-rule="evenodd" in your scenario:









  • Use a . This works similar to the tag you used and doesn't need a element either:















  • You could use a ` element and define the entire shape if needed, but that seems a bit counter intuitive unless you're using a tool to make the SVG instead of drawing it by hand.

Code Snippets

<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<mask id="a">
<circle cx="50" cy="50" r="50" fill="#fff"/>
<rect x="50" width="5" height="100%"/>
</mask>
<rect width="100" height="100" fill="gray" mask="url(#a)" />
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
    <mask id="a">
        <circle cx="50" cy="50" r="50" fill="#fff"/>
        <rect x="50" width="5" height="100%"/>
    </mask>
    <rect width="100" height="100" fill="gray" mask="url(#a)" />
</svg>

Context

StackExchange Code Review Q#106912, answer score: 8

Revisions (0)

No revisions yet.