给定两个可以多次嵌套的svg元素,应用了不同的转换,甚至在不同的svg fragments中,我如何移动一个(使用javascript)以使它以另一个为中心?
对于下面的示例,我想移动红色方块,使其在蓝色方块内居中(不改变其形状的任何其他内容)。
注意: javascript应该是通用的,以便在更改 下面的某些转换属性后它仍然有效
var big_rect = document.getElementById('big_rect');
var small_rect = document.getElementById('small_rect');
var sm_box = small_rect.getBBox();
console.log(sm_box);
// get center of rect in its coordinate system
var pnt = big_rect.ownerSVGElement.createSVGPoint();
pnt.x = big_rect.x.baseVal.value + big_rect.width.baseVal.value/2;
pnt.y = big_rect.y.baseVal.value + big_rect.height.baseVal.value/2;
// following lines unrotate the smaller rect,
// and don't center it on larger one anyway
/*
big_rect.parentNode.appendChild(small_rect);
small_rect.setAttribute('transform','translate(' +
(pnt.x - sm_box.width / 2) + ',' +
(pnt.y - sm_box.height / 2) + ')'
);
*/

<svg viewbox="50 50 250 250" height="250" width="250">
<g transform="translate(10,10) scale(2.5)">
<svg viewbox="0 0 500 500">
<g transform="translate(30,30) scale(0.5)">
<rect transform="translate(50,50)" id="big_rect" x=50 y=100 height=350 width=350 fill="blue" />
</g>
</svg>
</g>
<g transform="scale(1.5) translate(15,15)">
<svg viewbox="0 0 300 300">
<g id="small_rect" transform="rotate(45)">
<rect x="150" y="0" width="20" height="20" fill="red" />
<g>
</svg>
</g>
</svg>
&#13;
答案 0 :(得分:0)
问题是你的small_rect id在group元素上。你应该在组内定位rect元素。