通过javascript将<text>附加到<svg>

时间:2016-04-05 01:05:56

标签: javascript html d3.js svg

我正在研究SVG并且有一个非常简单的问题,我真的在努力。 如何将文本追加到svg标签? 我想达到以下结果:

Picture

我这样做:

svg.append("text")
        .attr("x", width / 2)
        .attr("y", height - marginBottom / 1 * 2 )
        .text("text 2")
        .attr("fill","#808080")
        .attr("text-anchor","middle")
        .css("font-size", "14px");

但浏览器显示错误:

  

未捕获的TypeError:   svg.append(...)。ATTR(...)。ATTR(...)。文本(...)。ATTR(...)。ATTR(...)。CSS   不是一个功能。

<line> svg.append同时工作:

svg.append("line")
     .attr("y1", height - marginBottom / 3 * 2 )
     .attr("y2", height - marginBottom / 3 * 2 )
     .attr("x1", marginLeft / 3 * 2 )
     .attr("x2", width - 20 )
     .attr("stroke-width", 1)
     .attr("stroke", "#5A97C3");

请帮助我理解。

2 个答案:

答案 0 :(得分:2)

正如错误所解释的:没有名为css的函数,我认为你的意思是stylesvg.style("font-size", "14px");

答案 1 :(得分:0)

不确定这是否是您正在寻找的,但您可以将SVG放入容器(例如div)并在div中添加文本元素。例如:

#myDiv{position:relative;width:200px;color:yellow;border:1px solid green;}
.abs{position:absolute;}
#innerDiv1{top:0;left:0px;width:90px;height:15px;border:1px solid purple;}
#innerDiv2{bottom:10px;left:20%;}
.rotate {-webkit-transform: rotate(-90deg);-moz-transform: rotate(-90deg);-ms-transform: rotate(-90deg);-o-transform: rotate(-90deg);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv">
  <img id="mySvg" src="http://placekitten.com/200/200" />
  <div id="innerDiv1" class="abs rotate">Text One</div>
  <div id="innerDiv2" class="abs">Text Two</div>
</div>

旋转的文字在我的演示中很不稳定,但如果这个概念可以接受,我会将其作为练习。