![](/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.