SVG transform property

71 Views Asked by At

I am having some issues with transforming an SVG. What I am trying to do is have a rotated rectangle scale and move at the same time. So far I have not found a way to do this..

Situation is as follows:

I have a rectangle defined in HTML like this so it rotates around its center:

<rect class="rotate_rect" id="right_left_polyg" x="50" y="35" width="12" height="12" style="fill:#4A4A4A;stroke:#4A4A4A;stroke-width:2" transform="rotate(45,56,41)"/>

I use velocity.js as my animation library, but the problem is more of a general nature. Issue is that when I try to move the rectangle to the right it moves down to the right. This is because my x-value I am changing, is also contained in the rotate function.

I also tried the following, but this does not react as I hoped.

.rotate_rect{
    transform: rotate(45deg);
    transform-origin: center;
}

Is there a way I can define a rotate function without having to specify the x-value?

To make it easily reproducable, here is my rectangle.. I have defined the class as above..

<rect class="rotate_rect" id="right_left_polyg" x="50" y="35" width="12" height="12" style="fill:#4A4A4A;stroke:#4A4A4A;stroke-width:2"/>

Is there a way to do this so the rectangle rotates around its center axis and x-value stays out of the rotate function?

1

There are 1 best solutions below

1
Ouroborus On

Build the rectangle so that its center is at 0, 0 and use translate() to move it before rotating it. (Technically moving after rotating due to transform semantics having operations applied from the innermost to the outermost.)

For example:

<rect x="-6" y="-6" width="12" height="12" transform="translate(56,41) rotate(45)" class="rotate_rect" id="right_left_polyg" style="fill:#4A4A4A;stroke:#4A4A4A;stroke-width:2" />

Or:

<g transform="translate(56,41)">
  <rect x="-6" y="-6" width="12" height="12" transform="rotate(45)" class="rotate_rect" id="right_left_polyg" style="fill:#4A4A4A;stroke:#4A4A4A;stroke-width:2" />
</g>