Luke
Luke

Reputation: 19971

Is it possible to get the XML of an SVG image using JavaScript?

My goal is to load an SVG image in JavaScript and have it both as an image and the underlying SVG XML.

I can load the image like...

var myImage = new Image();
myImage.src = "cat.svg";

Now after I have the image, how can I access the underlying XML that makes up the SVG image?

The only solution I've come up with is to load it again via ajax:

$(myImage).one("load", function(){
    $.ajax({
        url :       "cat.svg",
        cache :     true, 
        dataType :  "xml"
    }).fail(function( jqXHR, textStatus, errorThrown ) {
        console.error("Ajax failure loading image.");
    }).done(function( data, textStatus, jqXHR ){
        console.log("Got the image's SVG XML:", $(data).find('svg'));
    });
});

But I feel like there might be a better way to do this.

Upvotes: 4

Views: 4159

Answers (3)

Use jQuery, Tested on chrome and firefox

$('#svgBase').html( '<circle cx="20" cy="20" r="10" stroke="black" stroke-width="2" fill="red"></circle> <circle cx="50" cy="20" r="10" stroke="black" stroke-width="2" fill="green"></circle>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<svg id="svgBase"></svg>

Upvotes: 0

cloudfeet
cloudfeet

Reputation: 12873

There is no way to extract the image source from the Image object.

The AJAX solution included in your question is the only way to obtain the source.

If you want to only load the image once, then perhaps you could fetch it first using AJAX, and then use the fetched XML to render the image (e.g. adding to the document as inline SVG, or setting the source to a data: or Blob URL).

Upvotes: 5

Sebastian Bork
Sebastian Bork

Reputation: 546

As i know the svg will be impreted as soon as it get loaded. Therefore i would suggest, that your way is quite the only possible left.

All libs i know (snap.svg, svg.js, etc.) work only with the interpreted code of an svg. Even if it would boost performance on some degrees they relie on manipulating the interpreted code ... so i would guess there is no way to get the raw code out of an interpreted svg.

Upvotes: 1

Related Questions