Hi all,
I am trying to display an SVG string, (passed via function argument). The idea is to get a string, which is a valid SVG, make it a fragment and append to an <svg> element.
My function is as follows:
function load_fragment(svg_frag){
console.log("Inside load_fragment");
var s = Snap("#svg");
console.log("Going to append fragment");
//var f = Snap.fragment(svg_frag);
var f = Snap.parse(svg_frag);
s.append(f)
console.log("Fragment appended");
}
The HTML fragment referred is as follows:
<svg id="svg" width="400" height="400">
<defs></defs>
</svg>
SVG string (svg_frag) is:
<svg version="1.1" id="test" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="312px" height="300px" viewBox="0 0 260 250" enable-background="new 0 0 260 250" xml:space="preserve">
<g>
<rect x=".1" y=".1" width="99.8" height="29.8" fill="none" stroke="blue" stroke-width=".2" />
</g>
</svg>
My expectation is that after load_fragment runs, I should be able to see a blue rectangle, but the HTML shows the following:
<svg id="svg" width="400" height="400">
<defs></defs>
<desc>Created with Snap</desc>
<svg version=&quot;1.1&quot; id=&quot;test&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; x=&quot;0px&quot; y=&quot;0px&quot; width=&quot;312px&quot; height=&quot;300px&quot; viewBox=&quot;0 0 260 250&quot; enable-background=&quot;new 0 0 260 250&quot; xml:space=&quot;preserve&quot;&gt;
<g&gt;
<rect x=&quot;.1&quot; y=&quot;.1&quot; width=&quot;99.8&quot; height=&quot;29.8&quot; fill=&quot;none&quot; stroke=&quot;blue&quot; stroke-width=&quot;.2&quot; /&gt;
</g&gt;
</svg&gt;
</svg>
All three debug messages are printed in javascript console, and thus the function is indeed getting executed.
Inside load_fragment
Going to append fragment
Fragment appended
If I use Snap.load() instead of Snap.fragment() or Snap.parse() the code works as a charm:
function load_svg(svg_frag){
var s = Snap("#svg");
Snap.load("test.svg", function (f) {
s.append(f);
});
}
and contents of the test.svg is same as the svg_frag string.
When the load_svg function runs, the contents of the HTML is as follows:
<svg id="svg" width="400" height="400">
<defs></defs>
<desc>Created with Snap</desc>
<svg version="1.1" id="test" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="312px" height="300px" viewBox="0 0 260 250" enable-background="new 0 0 260 250" xml:space="preserve">
<g>
<rect x=".1" y=".1" width="99.8" height="29.8" fill="none" stroke="blue" stroke-width=".2"></rect>
</g>
</svg>
</svg>
Obviously Snap.load() correctly loads the SVG and places it as SVG elements, while Snap.fragment() and Snap.parse() places the SVG as escaped string.
I am not sure if I am using Snap.fragment() and Snap.parse() correctly or if there is any thing I am missing here.
So my question is How can I display an SVG string using Snap?
thanks and regards,
raj