user3756754
user3756754

Reputation: 65

How to preserve spaces in svg text

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);

Upvotes: 5

Views: 4994

Answers (1)

Robert Longson
Robert Longson

Reputation: 124089

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");

Upvotes: 8

Related Questions