How to set correct Inline SVG Circle coordinates

Viewed 672

I can make an inline SVG circle like this:

 <svg height="100" width="100">
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
    </svg> 

However, I'm struggling to understand the cx and cy and height and width properties.

What I want to achieve is a 15x15px circle that has no free space around it, but I can't seem to get it right.

  • <svg height="15" width="15"><circle cx="0" cy="0" r="9" stroke="black" stroke-width="1" fill="#c0c0c0" /></svg>
    This one only shows the bottom right corner
  • <svg height="15" width="15"><circle cx="7.5" cy="7.5" r="9" stroke="black" stroke-width="1" fill="#c0c0c0" /></svg> This one cuts the circle to a square

What is the correct way to achieve what I want? You can try for yourself here: https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_circle

2 Answers

Let's make the SVG canvas borders visible for clarity. To do this, write a CSS style in the header of the SVG fil

style="border:1px solid"

<svg height="100" width="100" style="border:1px solid">
  <circle id="circ" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg> 

The next step is to define the parameters width, height, x, y for the bounding rectangle of the circle using the JS getBBox() method

<svg height="100" width="100" viewBox="0 0 100 100" style="border:1px solid">
  <circle id="circ" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg> 
<script>
let bb = circ.getBBox();
console.log(bb);
</script>

You can see that the width of the rectangle is 80px padding from the beginning of the SVG canvas 10px, total size is 10 + 80 + 10 = 100px

If you want there to be no white space around the svg element, you need to remove these margins and add space to fit a 3px circle stroke

<svg height="84" width="84" viewBox="0 0 84 84" style="border:1px solid">
  <circle id="circ" cx="42" cy="42" r="40" stroke="black" stroke-width="3" fill="red" />
</svg> 
<script>
let bb = circ.getBBox();
console.log(bb);
</script>

The border around the SVG canvas can be removed as it was used to visually debug positioning

In the first case the root element has a height and width of 15 so you can see a portion of the x axis from 0 to 15 and the same for the y axis. A circle centred at the origin will therefore only have the bottom right corner visible as that's the only part of the circle within the root element canvas.

As to the second circle 7.5 - 9 (the radius) - 0.5 (1/2 the stroke width) < 0 and 7.5 + 9 + 0.5 > 15 so the circle is simply bigger than the outer SVG element canvas.

Related