How to set transform origin in SVG

I need to resize and rotate certain elements in SVG document using javascript. The problem is, by default, it always applies the transform around the origin at (0, 0) – top left.

How can I re-define this transform anchor point?

I tried using the transform-origin attribute, but it does not affect anything.

This is how I did it:

svg.getDocumentById('someId').setAttribute('transform-origin', '75 240');

It does not seem to set the pivotal point to the point I specified although I can see in Firefox that the attribute is correctly set. I tried things like center bottom and 50% 100% with and without parenthesis. Nothing worked so far.

Can anyone help?


Solution 1:

To rotate use transform="rotate(deg, cx, cy)", where deg is the degree you want to rotate and (cx, cy) define the centre of rotation.

For scaling/resizing, you have to translate by (-cx, -cy), then scale and then translate back to (cx, cy). You can do this with a matrix transform:

transform="matrix(sx, 0, 0, sy, cx-sx*cx, cy-sy*cy)"

Where sx is the scaling factor in the x-axis, sy in the y-axis.

Solution 2:

svg * { 
  transform-box: fill-box;
}

applying transform-box: fill-box will make an element within an SVG behave as a normal HTML element. Then you can apply transform-origin: center (or something else) as you would normally

that's right, transform-box: fill-box. These days, there's no need for any complicated matrix stuff

Solution 3:

If you can use a fixed value (not "center" or "50%"), you can use CSS instead:

-moz-transform-origin: 25px 25px;
-ms-transform-origin:  25px 25px;
-o-transform-origin: 25px 25px;
-webkit-transform-origin:  25px 25px;
transform-origin: 25px 25px;

Some browsers (like Firefox) won't handle relative values correctly.