Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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??

like image 517
zeacuss Avatar asked Feb 14 '12 17:02

zeacuss


People also ask

Can JavaScript be applied to SVG?

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.

Can an SVG have text?

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'.

How do I add text to SVG rect?

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.


2 Answers

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/.

like image 180
Bill Avatar answered Sep 25 '22 01:09

Bill


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);
like image 44
Casey OConnor Avatar answered Sep 27 '22 01:09

Casey OConnor