Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve spaces in svg text

Tags:

svg

snap.svg

To preserve spaces in a textelement of svg, one should use 'xml:space="preserve"' as an attribute of the text (jsfiddle). However, it isn't working. What am I doing wrong?

    // init snap
    var svgElement=document.getElementById("mainSvgId");
    var s = Snap(svgElement).attr({height: 300, width: 300});

    // greate group with rectanle
    var parentGroup=s.g().attr({id: "parent"});
    var rect1 = s.rect(0, 0, 200, 200).attr({fill: "#bada55"});
    parentGroup.add(rect1);

    // add text with preserve attribute
    var text = s.text(0, 20, "   text1    text2");
    text.node.setAttribute("xml:space", "preserve");
    parentGroup.add(text);
like image 594
user3756754 Avatar asked Aug 18 '14 10:08

user3756754


1 Answers

You're almost there. You need to properly create the attribute in the xml namespace for which you need setAttributeNS rather than setAttribute

text.node.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve");
like image 76
Robert Longson Avatar answered Oct 18 '22 12:10

Robert Longson