SVG Text rotation

SivaRajini picture SivaRajini · May 23, 2013 · Viewed 13.9k times · Source

I have a text with textContent "Design", that was transformed with css to be rotated 90 degree around the center (100,100), so it appears vertically. It rotate the entire coordinate system around the center, I want the element (ie “Design”) alone should rotate

Original position:

enter image description here

Result:

enter image description here

Expected :

enter image description here

SVG:

<svg>
<text x="70" y="30" width="64" height="16" fill="black" transform="rotate(90,100,100)">Design</text>
</svg>

What is the problem ? why text element x position changed ? how could i rotate the text in fixed x-position ?

i want to rotate a text in fixed x-position ?

Thanks,

Siva

Answer

Cyrille picture Cyrille · Jun 6, 2020

If you would like text at 100,100 rotated 90 degrees then try the following:

<svg>
  <text text-anchor="middle" transform="translate(100,100) rotate(90)">Design</text>
</svg>

This is much more straight-forward than the alternatives.

Keep in mind that the order of the transform parameters, translate and rotate, matters.

See the snippet below to see how it alters the outcome.

.translate {
  stroke: green;
  stroke-width: 2;
  fill: none;
  }
  
.rotate {
  stroke: red;
  stroke-width: 2;
  fill: none;
  }
  
.reference {
  stroke: blue;
  border: solid 1px blue;
  }
<svg class="reference" width="250" height="170" viewBox="-125 -25 250 170">
  <rect x="0" y="0" width="100" height="100" fill="none" stroke="black"/>
  <line class="translate" x1="0" x2="100" y1="0" y2="100"/>
  <circle class="rotate" cx="100" cy="100" r="3"/>
  <text text-anchor="middle" class="reference">0,0</text>
  <text text-anchor="middle" transform="translate(100,100) rotate(90)">TR</text>
</svg>

<svg class="reference" width="250" height="170" viewBox="-125 -25 250 170">
  <rect x="0" y="0" width="100" height="100" fill="none" stroke="black"/>
  <path class="rotate" d="M -100 100 A 141.1 141.1 0 0 0 100 100"/>
  <line class="translate" x1="0" x2="-100" y1="0" y2="100"/>
  <text text-anchor="middle" class="reference">0,0</text>
  <text text-anchor="middle" transform="rotate(90) translate(100,100)">RT</text>
</svg>