简体   繁体   中英

Text in SVG does not appear

I`m trying to add text to a svg element with javascript.

Here is my javascript code:

var svg=document.getElementById("svgtext");
var newText = document.createElementNS(svg,"text");
newText.setAttributeNS(null,"x",0);     
newText.setAttributeNS(null,"y",50); 
newText.setAttributeNS(null,"font-size","100");
newText.setAttributeNS(null,"fill","black");
var textNode = document.createTextNode("Hello World");
newText.appendChild(textNode);
document.getElementById("gText").appendChild(newText);

and this is the HTML

         <svg id="svgtext" width=160px height=250px>
              <g id="gText">
                  <text x="0" y="15" fill="black">SVG!</text> 
              </g>
         </svg>

As you can see if I add manually some text, it works perfectly. When I try with javascript I can see it present in Chrome's inspector tool, but it just does not appear on the screen.

You are passing the wrong value to the first argument of createElementNS. It should be as below.§

 var newText = document.createElementNS("http://www.w3.org/2000/svg", "text"); newText.setAttributeNS(null,"x",0); newText.setAttributeNS(null,"y",50); newText.setAttributeNS(null,"font-size","100"); newText.setAttributeNS(null,"fill","black"); var textNode = document.createTextNode("Hello World"); newText.appendChild(textNode); document.getElementById("gText").appendChild(newText); 
  <svg id="svgtext" width="160px" height="250px"> <g id="gText"> <text x="0" y="15" fill="black">SVG!</text> </g> </svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM