更改SVG边界框位置

时间:2014-09-03 06:19:59

标签: svg shapes

我有一个svg圆圈和一个svg矩形,我想把矩形放在圆圈内,使矩形位置在圆心。 我知道' getBBox()'获取边界框大小和位置的方法,但我无法设置大小和位置。 我的问题是矩形的中心似乎是它的左上角。 这是示例代码:

<svg width="500" height="500">
<circle id="aaa" r="100" fill="red" transform="translate(150,150)"></circle>
<rect id="circle2" width="50" height="50" fill="green" transform="translate(150,150)">   </rect>
</svg>

3 个答案:

答案 0 :(得分:1)

如果未明确设置,则圈子的cxcy将为null,实际上它们都是0。从圆的中心点,您可以使用以下公式导出矩形的top-left点(位置):

x = cx - width / 2;
y = cy - height / 2;

因此,您可以尝试使用以下脚本将矩形设置在圆的中心:

var rect = document.getElementById('circle2');
var circ = document.getElementById("aaa");
var cx = circ.getAttribute("cx");
var cy = circ.getAttribute("cy");
if(cx == null) cx = 0;
if(cy == null) cy = 0;
var w = parseInt(rect.getAttribute("width"));
var h = parseInt(rect.getAttribute("height"));
rect.setAttribute("x", cx - w/2);
rect.setAttribute("y", cy - h/2);

Demo

答案 1 :(得分:0)

在您的示例SVG中,您将创建以原点为中心的圆,然后将其移动到150,150。看起来你正试图在广场上做同样的事情,除非你没有正确地将它集中在原点上。

如果正确定位正方形,它将起作用。该方块需要从-25,-25扩展到25,25。见下文:

<svg width="500" height="500">
  <circle r="100" fill="red" transform="translate(150,150)"></circle>
  <rect x="-25" y="-25" width="50" height="50" fill="green" transform="translate(150,150)">   </rect>
</svg>

Fiddle here

答案 2 :(得分:0)

我的建议:通常更容易围绕原点创建,<g>和两个translate。旋转也被简化,因为它只是围绕原点旋转。

  1. 围绕原点创建圈子(即:cx=0cy=0
  2. 在原始<rect>
  3. 周围创建(x,y), (-x,y), (-x,-y), (x,-y)
  4. <g>以及此<circle><rect>周围添加translate代码。
相关问题