简体   繁体   English

在div容器内添加SVG文本

[英]Adding SVG text inside a div container

Sorry, this question may be a classical issue but I try to debug the following JS (I am a beginner with SVG handling) : 抱歉,这个问题可能是一个经典问题,但是我尝试调试以下JS(我是SVG处理的初学者):

script to debug 调试脚本

In a first time, I would like to create a SVG element in which I could put a text. 第一次,我想创建一个可以在其中放置文本的SVG元素。 I have followed this example on this link 我在此链接上关注了此示例

Here what I have done : 在这里,我做了什么:

HTML : HTML:

<div id="containerCanvas">
</div>

JAVASCRIPT : 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 : CSS:

#containerCanvas{
position: relative;
top: 0;
left: 0;
margin: 20px;
}

Unfortunately, nothing appears into result window on jsfiddle (I expect the text "Need help" with font-size = 20 and red color ). 不幸的是,jsfiddle的结果窗口中什么都没有出现(我希望文本“ Need help”( font-size = 20red color ))。

Anyone could see what's wrong ? 有人看到错了吗?

After taking a closer look, the html that is currently being generated is: 仔细观察之后,当前正在生成的html是:

<text x="1" y="2" font-size="20">Need help</text>

However it should be enclosed by an svg tag, ie: 但是,它应该用svg标记括起来,即:

<svg height="200" width="200">
  <text x="1" y="2" font-size="20" fill="black">Need help</text>
</svg>

Updated Js 更新的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);

Hope it helps... https://jsfiddle.net/v4zhLgmL/20/ 希望对您有所帮助... https://jsfiddle.net/v4zhLgmL/20/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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