svg

Rotate rectangle around its own center in SVG


I have following piece of code :

<svg>

<defs>
<rect id = "myRect"
      x = "10"
      y = "10"
      height = "120"
      width = "120"
      stroke-width = "2px"
      stroke = "red"
      fill = "blue" />

</defs>


<g transform = "translate(100,30)">
  <use xlink:href = "#myRect" />
</g>

<g transform = "translate(100, 100) rotate(45 ? ?)">

  <rect id = "myRect"
      x = "10"
      y = "10"
      height = "120"
      width = "120"
      stroke-width = "2px"
      stroke = "green"
      fill = "yellow" />
</g>

</svg>

When I translate rectangle without rotation, it is working fine. But when I rotate it, I wanted to rotate it around its center axis point. What should I need to pass to rotate attribute?


Solution

  • You would have to set the center as the center of the filled element. Like this:

    svg .rotate {
      transform-box: fill-box;
      transform-origin: center;
      transform: rotate(45deg);
    }