Home > Back-end >  Rounding the corners of an SVG
Rounding the corners of an SVG

Time:02-11

I'm using a package that generates a rectangular Treemap with this structure:

  • svg (wrapper with width=100% and height=100%)
    • svg (the outer rectangle of the Treemap, also width=100% and height=100%)
      • g (one for each Treemap node)
        • rect
        • clipPath
        • text

svg element I need to round the four corners of the entire Treemap (not the rx ry of each rect within).

Is it possible to do that by creating a clipPath either as a child of the wrapper or the inner svg that defines a rounded rectangle? If so, can it expose whatever the background color is behind the svg?

UPDATE: @web-tiki - here's what the code looks like...

<svg width="100%" height="100%" style="border-radius: 4px;">
  <svg width="100%" height="100%">
  <!-- ... -->

Looks great on Safari and Firefox but Chrome appears to ignore it. Wondering if it's a combination of Carbon Charts Treemap and Chrome?

CodePudding user response:

The easiest solution is probably to use the border-radius CSS property on the svg wrapper element. It will allow you to clip round corners on your svg element and expose the background color behind the svg. Here is an example :

body {
  background: darkorange;
}

#wrapper {
  display: block;
  width: 100%;
  border-radius: 50px;
  overflow: hidden;
  border:10px solid pink;
}
<svg id="wrapper" viewBox="0 0 100 100">
  <svg>
    <rect fill="teal" x="0" y="0" width="100" height="100"/>
   </svg>
</svg>

On a side note, you can also wrap the entire svg inside a div and apply the border-radius on that div like this :

body {
  background: darkorange;
}

#wrapper {
  border-radius: 50px;
  overflow: hidden;
  border: 10px solid pink;
}
<div id="wrapper">
  <svg viewBox="0 0 100 100">
    <svg>
      <rect fill="teal" x="0" y="0" width="100" height="100"/>
     </svg>
  </svg>
</div>

CodePudding user response:

Found I could add this to the wrapper svg to get the effect I wanted:

<defs>
  <clipPath id="smallBox">
    <path d="M 0 4 A 4 4 0 0 1 4 0 L 446 0 A 4 4 0 0 1 450 4 L 450 346 A 4 4 0 0 1 446 350 L 4 350 A 4 4 0 0 1 0 346 Z"/>
  </clipPath>
</defs>

then added style="clip-path: url(#smallBox);" to the inner svg.

The path was generated with this code (source: https://gist.github.com/danielpquinn/dd966af424030d47e476)

const roundedRect = (w, h, r) => 
    'M 0 '   r
      ' A '   r   ' '   r   ' 0 0 1 '   r   ' 0'
      ' L '   (w - r)   ' 0'
      ' A '   r   ' '   r   ' 0 0 1 '   w   ' '   r
      ' L '   w   ' '   (h - r)
      ' A '   r   ' '   r   ' 0 0 1 '   (w - r)   ' '   h
      ' L '   r   ' '   h
      ' A '   r   ' '   r   ' 0 0 1 0 '   (h - r)
      ' Z'

console.log(roundedRect(450,350,4))
  • Related