抱歉,这个问题可能是一个经典问题,但我尝试调试以下 JS(我是 SVG 处理的初学者):
第一次,我想创建一个 SVG 元素,我可以在其中放置文本。我在 this link 上关注了这个例子
这是我所做的:
HTML:
<div id="containerCanvas">
</div>
JavaScript :
var svgNS = "http://www.w3.org/2000/svg";
var x=1;
var y=2;
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x",x);
newText.setAttributeNS(null,"y",y);
newText.setAttributeNS(null,"font-size","20","fill","red");
newText.innerHTML = "Need help";
document.getElementById("containerCanvas").appendChild(newText);
CSS:
#containerCanvas{
position: relative;
top: 0;
left: 0;
margin: 20px;
}
不幸的是,在 jsfiddle 的结果窗口中没有出现任何内容(我希望文本“需要帮助”带有 font-size = 20
和 red color
)。
谁能看出哪里出了问题?
最佳答案
仔细一看,目前正在生成的html是:
<text x="1" y="2" font-size="20">Need help</text>
但是它应该被一个 svg 标签括起来,即:
<svg height="200" width="200">
<text x="1" y="2" font-size="20" fill="black">Need help</text>
</svg>
更新的 Js
var svgNS = "http://www.w3.org/2000/svg";
var x=30;
var y=20;
var svgEl = document.createElementNS(svgNS,"svg");
svgEl.setAttributeNS(null,"height",200);
svgEl.setAttributeNS(null,"width",200);
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x",x);
newText.setAttributeNS(null,"y",y);
newText.setAttributeNS(null,"font-size","20");
newText.setAttributeNS(null,"fill","red");
newText.innerHTML = "Need help";
svgEl.appendChild(newText);
document.getElementById("containerCanvas").appendChild(svgEl);
希望对您有所帮助... https://jsfiddle.net/v4zhLgmL/20/
关于javascript - 在 div 容器中添加 SVG 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41309338/