I'm trying to add a text element to the <g>
element in a SVG document using javascript
my code looks like this
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??
Since SVG images can be inlined in HTML, we can manipulate them with JavaScript. This means that we can animate parts of an image from code, make it interactive, or turn things around and generate graphics from data.
A text content element is an SVG element that causes a text string to be rendered onto the canvas. The SVG text content elements are: 'text', 'textPath' and 'tspan'.
If you want to display text inside a rect element you should put them both in a group with the text element coming after the rect element ( so it appears on top ). The group fits to its content not the other way. I think the elements are still relative to the parent svg.
I think you need to create a text node to hold the string and append that to the SVG text element.
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/.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With