[英]Text in SVG does not appear
我正在尝试使用javascript将文本添加到svg元素。
这是我的JavaScript代码:
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);
这是HTML
<svg id="svgtext" width=160px height=250px>
<g id="gText">
<text x="0" y="15" fill="black">SVG!</text>
</g>
</svg>
如您所见,如果我手动添加一些文本,它会完美地工作。 当我尝试使用javascript时,我可以在Chrome的检查器工具中看到它,但是它没有出现在屏幕上。
您将错误的值传递给createElementNS的第一个参数。 它应该如下所示。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.