2011-07-17 35 views
126

我想在 SVG rect的内部显示一些文本。可能吗?SVG:正文内的文本

我试图

<svg xmlns="http://www.w3.org/2000/svg"> 
    <g> 
    <rect x="0" y="0" width="100" height="100" fill="red"> 
     <text x="0" y="10" font-family="Verdana" font-size="55" fill="blue"> Hello </text> 
    </rect> 
    </g> 
</svg> 

但它不工作。

+5

可能重复的(http://stackoverflow.com/questions/5449899/insert-text-between-a-rectangle-drawn-in-svg) – Jonas

回答

163

这是不可能的。如果你想在rect元素中显示文本,你应该把它们放在一个组中,其中的文本元素在rect元素之后(所以它出现在顶部)。

<svg xmlns="http://www.w3.org/2000/svg"> 
 
    <g> 
 
    <rect x="0" y="0" width="100" height="100" fill="red"></rect> 
 
    <text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text> 
 
    </g> 
 
</svg>

+10

有没有办法可以在rect上手动设置高度和宽度? –

+0

取决于情况以及“手动”的含义。如果你喜欢,你可以用JavaScript编写脚本(参见下面的narendra的回答) – KeatsKelleher

+8

使用我的html知识 - 在这里可能不适用 - 看起来'g'元素在这里有一个隐含的大小,我希望矩形扩展它的大小。 –

54

编程使用D3:[在SVG绘制一个矩形之间插入文本]

body = d3.select('body') 
svg = body.append('svg').attr('height', 600).attr('width', 200) 
rect = svg.append('rect').transition().duration(500).attr('width', 150) 
       .attr('height', 100) 
       .attr('x', 40) 
       .attr('y', 100) 
       .style('fill', 'white') 
       .attr('stroke', 'black') 
text = svg.append('text').text('This is some information about whatever') 
       .attr('x', 50) 
       .attr('y', 150) 
       .attr('fill', 'black') 
+6

这会产生*显示OP *想要的标记,但它不会执行OP正在尝试执行的操作(这不合法)。这仍然产生''。 –

+1

Javascript!= SVG。问题用svg,文本和rect标记。没有任何信息表明用户可以访问编程语言。 (自从我来到这里寻找一个静态解决方案时做出这个评论。) – aioobe

4
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"> 
    <g> 
    <defs> 
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"> 
     <stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" /> 
     <stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" /> 
    </linearGradient> 
    </defs> 
    <rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" /> 
    <text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text> 
    </g> 
</svg>