Mostafa Talebi
Mostafa Talebi

Reputation: 9183

Rotating a SVG path using CSS3 around its own center

I have a set of SVG path, one of them is as follows:

<path id="GOL" class="st0" d="M37.5,430.5l-12.4-12.4v-13.3h-4.2c-7.2,0-13.9,2.5-18.7,7.5c-4.7,4.9-7.3,11.3-7.3,18.3
    c0,7,2.6,13.5,7.3,18.3c4.8,5,11.4,7.6,18.6,7.6l4.2,0v-13.7L36.7,430.5z M19.7,435.3l-4.9-4.9l4.9-4.9l4.9,4.9L19.7,435.3z
     M2.4,430.5c0-8.4,5.6-15.1,13.1-16.9v3.8L2.4,430.5l13.1,13.1v3.8C8,445.6,2.4,438.9,2.4,00.5z"></path>

I try to make a rotate-animation with the below code:

.stuck #GOL
{
  fill: red;
  transform: rotate(90deg);
}

#GOL
{
  transition-property: all;
  transition-duration: 2s;
}

The problem is that the path rotates around a distance center which is not regular. I want it to rotate around its own center. I have to use CSS3 (so I can't use svg's own rotate() function).

Upvotes: 5

Views: 14514

Answers (2)

Paul LeBeau
Paul LeBeau

Reputation: 101956

You can avoid the use of transform-origin and its associated browser issues by using nested transforms.

The basic idea is to transform the centre of rotation for the path to the origin (top left) of the SVG do the rotation and transform it back to its original position. You can achieve this with nested groups.

The centre of your crown shape is at approx (22, 432). So we can do:

<g transform="translate(22 432)">   // translate everything to the path's original position
  <g transform="rotate(90deg)">     // rotate (around the origin)
    <path transform="translate(-22 -432)"/>  // shift path to the origin
  </g>
</g>

Read the transforms from the inside (the path) to the outermost group.

Demo below:

#GOL
{
  fill: red;
  transform: rotate(90deg);
}

#GOL
{
  transition-property: all;
  transition-duration: 2s;
}
<svg width="500" height="500">

  <g transform="translate(22 432)">
    <g id="GOL">
      <path class="st0" d="M37.5,430.5l-12.4-12.4v-13.3h-4.2c-7.2,0-13.9,2.5-18.7,7.5c-4.7,4.9-7.3,11.3-7.3,18.3
    c0,7,2.6,13.5,7.3,18.3c4.8,5,11.4,7.6,18.6,7.6l4.2,0v-13.7L36.7,430.5z M19.7,435.3l-4.9-4.9l4.9-4.9l4.9,4.9L19.7,435.3z
     M2.4,430.5c0-8.4,5.6-15.1,13.1-16.9v3.8L2.4,430.5l13.1,13.1v3.8C8,445.6,2.4,438.9,2.4,00.5z"
        transform="translate(-22 -432)"></path>
    </g>
  </g>
</svg>

Upvotes: 1

Stewartside
Stewartside

Reputation: 20925

Have you tried using transform-origin in your CSS?

transform-origin: 50% 50%;

This will start any transform from the middle of the selector.

Upvotes: 2

Related Questions