Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge two shapes in svg?

Tags:

html

svg

I have two shapes: circle and rectangle. Want to convert them into one figure. Are there any ways to do that in SVG code?

 <svg width="400" height="400">
     <defs>
    <g id="shape" fill="none" stroke="red">
      <rect x="40" y="50" width="40" height="70" />
      <circle cx="50" cy="50" r="50" />
    </g>
  </defs>

  <use xlink:href="#shape" x="50" y="50"  />
  <use xlink:href="#shape" x="200" y="50" />

</svg>

Like this: like this

like image 540
misterioss Avatar asked Aug 28 '16 16:08

misterioss


People also ask

How do you combine shapes in Photoshop?

Combine shapes with the Shape Builder tool Select the shapes you want to combine. Select the Shape Builder tool in the Toolbar. The Shape Builder tool lets you combine or remove shapes you select. Drag across shapes to combine them.


1 Answers

For anyone looking for the answer to the actual question of how to combine two outlined shapes into a single outlined shape (rather than putting a drop shadow on the combined shape), here is a possible solution:

<svg width="400" height="400">
    <defs>
        <rect id="canvas" width="100%" height="100%" fill="white" />
        <rect id="shape1" x="40" y="50" width="40" height="70" />
        <circle id="shape2" cx="50" cy="50" r="50" />
        <mask id="shape1-cutout">
            <use href="#canvas"  />
            <use href="#shape1"  />
        </mask>
        <mask id="shape2-cutout">
            <use href="#canvas"  />
            <use href="#shape2"  />
        </mask>
    </defs>
    <use href="#shape1" stroke="red" fill="none" mask="url(#shape2-cutout)" />
    <use href="#shape2" stroke="red" fill="none" mask="url(#shape1-cutout)" />
</svg>

This essentially draws the circle with the rectangle shape cut out of it and draws the rectangle with the circle cut out of it. When you place these "punched out" shapes one on top of the other, you get what appears to be a single outlined shape.

Here's what the SVG actually does:

  1. It defines a white rectangle called "canvas" that is the same size as the SVG.
  2. It defines the two shapes that are to be combined ("shape1" and "shape2").
  3. It defines a mask for each shape that combines the canvas (which has a fill of white) with the shape (which has a fill of black by default). Note that when you apply a mask to a shape, the part of the shape that corresponds to the white area of the mask is shown, while the part that corresponds with black part is hidden.
  4. It draws each shape with the the mask of the other shape applied.
like image 94
devuxer Avatar answered Sep 20 '22 16:09

devuxer