Reputation: 155
I am studying SVG and have a very simple question that I am really struggling with. How to append text to a svg tag? I want to achieve the following result:
I am doing this:
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");
But the browser shows an Error:
Uncaught TypeError: svg.append(...).attr(...).attr(...).text(...).attr(...).attr(...).css is not a function.
But at the same time for <line>
svg.append
works :
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");
Please help me understand.
Upvotes: 0
Views: 1336
Reputation: 40038
Not sure if this is what you're looking for, but you can put the SVG into a container (e.g. a div) and add the text elements inside the div. Example:
#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>
Rotated text is wonky in my demo, but I'll leave that as an exercise if the concept is acceptable.
Upvotes: 0
Reputation: 2672
As the error explains: there's no function named css
, I think you meant style
: svg.style("font-size", "14px");
Upvotes: 2