Home > OS >  How to rotate svg component around its axis
How to rotate svg component around its axis

Time:10-13

I want to rotate the pointer around its axis of the following SVG component.

enter image description here

How could I achieve that. I have tried it with following method but it doesn't rotate around it.

<g id="Group 1" transform = "translate(100, 100) rotate(45 0 0)">
<path id="Point" fill-rule="evenodd" clip-rule="evenodd" d="M302.248 291.371L230.862 209.521L212.309 230.492L302.248 291.371Z" fill="#72A1E7"/>
</g>

CodePudding user response:

It is easier to:

  • rotate something if it can be centered around 0,0.
  • calculate the angle of the needle if you know the angle at the starting point.

Therefor the you could draw the needle like this, with the middle of the short line at 0,0 (yes, it is off-canvas) and then pointing at 6 o'clock:

svg {
  background-color: silver;
}
<svg width="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <g id="Group 1">
    <path id="Point" fill-rule="evenodd" clip-rule="evenodd"
    d="M -10 0 L 10 0 L 0 75 Z" fill="#72A1E7"/>
  </g>
</svg>

Now the needle can be moved to the center (or where ever) of the image:

svg {
  background-color: silver;
}
<svg width="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <g id="Group 1" transform="translate(100 100)">
    <path id="Point" fill-rule="evenodd" clip-rule="evenodd"
    d="M -10 0 L 10 0 L 0 75 Z" fill="#72A1E7"/>
  </g>
</svg>

The rotation can be done in different ways, but here I rotate the needle/path <path> itself to the imagined zero point of the meter and then use the group element <g> to give the meter a "value". So, here the calculation is that the meter takes up 300 deg, the zero value is at 30 deg (from 6 o'clock) and the max value is then at 330 deg. Here the value is 1/3 = 100 deg.

svg {
  background-color: silver;
}
<svg width="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <circle transform="rotate(120 100 100)" cx="100" cy="100" r="85"
  stroke="blue" stroke-width="5" stroke-dasharray="300 360" pathLength="360"
  fill="none" />
  <g id="Group 1" transform="translate(100 100) rotate(100)">
    <path id="Point" transform="rotate(30)" fill-rule="evenodd"
    clip-rule="evenodd" d="M -10 0 L 10 0 L 0 75 Z" fill="#72A1E7"/>
  </g>
</svg>

  •  Tags:  
  • svg
  • Related