How to set transform origin in SVG

Viewed 116512

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?

8 Answers
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

Setting the attribute (transform-origin="center") of the embedded element just inside the DOM did the trick for me

          <circle
          fill="#FFFFFF"
          cx="82"
          cy="81.625"
          r="81.5"
          transform-origin="center"
        ></circle>

Works well with using css transforms

You can build whatever you want around 0,0 origin, then put it into a group <g></g> and matrix-translate the whole group. Like that, the object will always rotate around 0,0 , but the whole group is moved (translated) elsewhere and translation matrix is applied after the rotation.

<g transform="matrix(1 0 0 1 160 200)">
  <polygon id="arrow-A" class="arrow" points="0,4 -90,0 0,-4 "/>
</g>


<style>

.arrow {
  transform: rotate(60deg);
}

/* OR */

#arrow-A {
  transform: rotate(60deg);
}

</style>

OR scripting: 

<script> 
  document.getElementById("arrow-A").setAttribute("transform", "rotate(60)");
</script>

This will create an arrow (eg. for a gauge), the broader end at [0,0] and move it to [160, 200]. Whichever rotation is applied to class "arrow", will rotate it around [160, 200].

Tested in: Chrome, Firefox, Opera, MS Edge

Related