![](/img/trans.png)
[英]How do I use one element of an SVG to change the opacity of another, in the same SVG?
[英]How do I dynamically centre one svg element on another with javascript
由于可以被嵌套多次,都采用了不同的变换,甚至是不同的两个SVG元素SVG片段 ,我将如何移动一个(使用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>
问题是您的small_rect ID位于group元素上。 您应该定位到组中的rect元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.