Rotate rectangle around its own center in SVG

2019-01-23 10:53发布

I have following piece of code :

<svg>

<defs>
<rect id = "myRect"
      x = "10"
      y = "10"
      height = "120"
      width = "120"
      stroke-width = "2px"
      stroke = "red"
      fill = "blue" />

</defs>


<g transform = "translate(100,30)">
  <use xlink:href = "#myRect" />
</g>

<g transform = "translate(100, 100) rotate(45 ? ?)">

  <rect id = "myRect"
      x = "10"
      y = "10"
      height = "120"
      width = "120"
      stroke-width = "2px"
      stroke = "green"
      fill = "yellow" />
</g>

</svg>

When I translate rectangle without rotation, it is working fine. But when I rotate it, I wanted to rotate it around its center axis point. What should I need to pass to rotate attribute?

标签: svg
3条回答
Deceive 欺骗
2楼-- · 2019-01-23 11:33

Nothing you just need to write the following code with the element in javascript:

element.rotate(angle Degree);
查看更多
不美不萌又怎样
3楼-- · 2019-01-23 11:50

You just need to add half the width/height of the rectangle to get its centre.

<g transform = "translate(100, 100) rotate(45 60 60)">

See transform documentation of the rotate function for more information.

查看更多
相关推荐>>
4楼-- · 2019-01-23 11:58

The accepted answer works if you are drawing the rectangle starting at point (0,0) which was the OP case. However for me it was not!

Here is what worked for me:

  • To get the rectangle coordinates i used $('#rectID').getBBox() method, should return [rect-height , rect-width , rect-y , rect x ]
  • The center point is ( rect-x + (rect-width/2) , rect-y + (rect-height/2) )

Here is a snippet i used on the browser console:

var coord = $('#elemID')[0].getBBox();
coord.x + (coord.width/2) +' '+ coord.y + (coord.height/2)
查看更多
登录 后发表回答