2011-12-19 22 views
4

我正在尝试编写一个SVG页面,其中有一个图标,右边是一个动态文本(这两者之间的距离是固定的)。图标具有固定的宽度和高度,但文字的宽度可能有所不同。在SVG容器中对齐多个元素

两个元素都被一个组包围,并且它们应该集中在那里。该小组还包含一个也位于中心的自由文本。

.-------------------------------------. 
|          | 
|    some text    | 
|          | 
| .----.       | 
| | | blah blah blah blah blah | 
| `----´       | 
`-------------------------------------´ 

.-------------------------------------. 
|          | 
|    some text    | 
|          | 
|  .----.      | 
|  | | blah blah blah  | 
|  `----´      | 
`-------------------------------------´ 

任何人都可以欣赏我的ASCII技能吗? ;)

我的方法是将图标和文本编译到一个组中,然后将该组中的一个放入父组中。标题文字也是。

我读到我可以将文本放在一个组中,但我没有找到对齐图像或实际组的方法。

<g id="MainGroup">  
    <text id="InfoText" x="90" y="0" width="320" text-anchor="middle" font-size="20" fill="#FFFFFF"/> 
    <g x="90" y="0" width="320" text-anchor="middle"> 
    <image id="UserIcon" x="0" y="25" width="48" height="48"/> 
    <text id="Username" x="58" y="55" font-size="22" fill="#FFFFFF"/> 
    </g>  
</g> 

我该怎么做?

请注意,我对这个SVG东西是全新的,所以我可能会错过显而易见的东西。如果我错过了您需要的一些信息,请随时索要。

回答

1

SVG中没有内置对齐方式。您必须通过javascript使用getBBox方法获取要居中的项目的宽度和容器的宽度,然后通过设置所包含项目的x属性来完成自我定位。

下面是一个例子

<svg width="320" height="200" onload="go()"> 
 
<g id="MainGroup"> 
 
    <rect stroke="black" width="100%" height="100%" fill="none"/> 
 
    <text id="InfoText" x="160" y="30" text-anchor="middle" font-size="20" fill="black">some text</text> 
 
    <g id="SubGroup" text-anchor="left"> 
 
    <rect id="UserIcon" x="0" y="25" width="48" height="48" fill="red" /> 
 
    <text id="Username" x="50" y="55" font-size="22" fill="black">blah blah blah</text> 
 
    </g>  
 
    <g id="SubGroup2" text-anchor="left"> 
 
    <rect id="UserIcon" x="0" y="25" width="48" height="48" fill="red" /> 
 
    <text id="Username" x="50" y="55" font-size="22" fill="black">blah blah blah blah blah</text> 
 
    </g>  
 
</g> 
 
<script> 
 
    function centre(element, y) { 
 
     element.setAttribute("transform", 
 
          "translate(" + (320 - element.getBBox().width)/2 + ", " + y + ")"); 
 
    } 
 
    function go() { 
 
     centre(document.getElementById("SubGroup"), 30); 
 
     centre(document.getElementById("SubGroup2"), 100); 
 
    } 
 
</script> 
 
</svg>

+0

好的,谢谢。 [SVG-Wiki]有一个例子(http://wiki.svg.org/index.php/GetBBox)。 – sjngm 2011-12-20 08:49:35

+0

@GusOst然后你需要通过[web.archive]去(https://web.archive.org/web/20111211055106/http://wiki.svg.org/index.php/GetBBox)。 – sjngm 2013-10-23 15:48:19