简体   繁体   English

在 javascript 中向 SVG 文档添加文本

[英]adding Text to SVG document in javascript

I'm trying to add a text element to the <g> element in a SVG document using javascript my code looks like this我正在尝试使用 javascript 将文本元素添加到 SVG 文档中的<g>元素我的代码如下所示

function addText(x,y,val){
    var newtxt = document.createElementNS("http://www.w3.org/2000/svg", "text");
    $newtxt = $(newtxt);
    $newtxt.attr('x',x);
    $newtxt.attr('y',y);
    $newtxt.attr('font-size','100');
    $newtxt.val(val);
    $newtxt.appendTo($('g'));
}

but when I run it the text is not shown.但是当我运行它时,文本没有显示。 the element is added to the <g> element, but the value is not set.. any ideas how to solve this??该元素已添加到<g>元素,但未设置值..有什么解决办法吗??

I think you need to create a text node to hold the string and append that to the SVG text element.我认为您需要创建一个文本节点来保存字符串并将其附加到 SVG 文本元素。

var svgNS = "http://www.w3.org/2000/svg";
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x",x);     
newText.setAttributeNS(null,"y",y); 
newText.setAttributeNS(null,"font-size","100");

var textNode = document.createTextNode(val);
newText.appendChild(textNode);
document.getElementById("g").appendChild(newText);

There's a working example at http://old.carto.net/papers/svg/manipulating_svg_with_dom_ecmascript/ .http://old.carto.net/papers/svg/manipulating_svg_with_dom_ecmascript/有一个工作示例。

var txt = document.createElementNS(svgNS, 'text');
txt.setAttributeNS(null, 'x', x);
txt.setAttributeNS(null, 'y', y);
txt.setAttributeNS(null,'font-size','100');
txt.innerHTML = val;
document.getElementById("g").appendChild(txt);

Additionally, if you want to update the text value dynamically then you could use textContent property.此外,如果您想动态更新文本值,则可以使用textContent属性。

const textNS = document.createElementNS("http://www.w3.org/2000/svg","text");
const textNode = document.createTextNode("Old Value");
textNS.appendChild(textNode);
document.body.appendChild(textNS);

textNS.textContent = "New Value";

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

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