views:

514

answers:

3

I have a rectangle in SVG that I need to rotate on a pivot from a specific point. The best way I can see to do this is transform to the xy of the pivot, rotate the degree, and then transform again. The problem is the xy of the second transform. I assume its going to take cos and sin to some extent, just not sure where or why.

*
|
|
|

would rotate -90degrees to

*---

Maybe im looking at this the wrong way, can anyone clearify?

+1  A: 

i think, you only need to negate coordinated for the first transform:

pseudocode:

g.transform(0,2);
g.rotate(90);
g.transform(0,-2);

fazo
that isnt true for all instances, it would need to be based on the angle
Dested
A: 

The SVG Spec section on coordinate system transformations nicely shows the transformation matrices and how to chain them.

ndim
A: 

If you use the SVG transform attribute rather than trying to code it yourself with javascript, all you need to do is center your shape with (0, 0) as the pivot.

For instance, in the example below, the center of the initial arc in the path is at the origin. The animation applies to that element, so it appears to spin in place, with the circle stationary. The translation on the containing group moves the center point of the rotation to the center of the image.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
    <g transform="translate(32, 32)" stroke="navy" fill="none">
        <path d="M -1 1.732 a 2 2 0 1 1 2 0 v 24 a 1 1 0 0 1 -2 0 Z">
            <animateTransform attributeName="transform" type="rotate"
                from="0" to="360" dur="1s" repeatDur="indefinite"/>
        </path>
    </g>
</svg>

The only calculation there is the 1.732 to get the center of the circle, the transformation matrix handles the angles. Note, you don't have to use SMIL with SVG, changing the angle from a javascript timeout works fine too.

gz