0

Is it possible to get a dataUrl (or simply the SVG source code) of an SVG image which is not inline SVG, but an external SVG file on the same domain?

I had a look at https://github.com/sampumon/SVG.toDataURL, but it only works for inline SVG, not for external SVG files.

To be clear, I am not looking to convert the SVG image to a PNG and then get the PNG's dataUrl, I need to get at the actual SVG code.

The solution would need to be open source and work in most modern browsers.

Here's a minimal version of what I'm trying to do:

<!DOCTYPE html>

<html>
<head>
<script type="text/javascript">

    function getSvgDataUrl(imgID) {

        // FIXME!!!

        return dataUrl;
    }

    function doTheThing() {
        result = getSvgDataUrl('foo');
        console.write(result);
    }

</script>
</head>

<body onload='doTheThing()'>
    <img src='myImage.svg' id='foo'>
</body>
</html>

I think the obvious thing to do here is to put the SVG image on a canvas and then get a dataURL from the canvas, like this:

source = new Image();
source.src = 'myImage.svg';
source.onload = function(event){
    c = document.getElementById('canvas');
    ctx = c.getContext('2d');
    ctx.drawImage(source,0,0,116,23);
    data = c.toDataURL('image/svg', 1.0);
    alert(data);
};

But this gives me a PNG dataURL, not SVG.

I also looked at XMLSerializer, which seemed promising, but I can't work out how to get at the internal SVG. Doing this:

svgImg = document.getElementById('foo');
s = new XMLSerializer();
console.log(s.serializeToString(svgImg));

Just gives the following console output:

<img xmlns="http://www.w3.org/1999/xhtml" src="myImage.svg" id="foo" />
user2852263
  • 539
  • 4
  • 5

1 Answers1

0

Justin Taddei gave the answer: it's fetch. I get the feeling it was dumb of me not to know this but on the other hand I bet I'm not the only one to get confused by this, so here's the code that worked:

async function getText(file) {
    let x = await fetch(file);
    let y = await x.text();
    console.log(y);
}

getText("myImage.svg");

There's info about fetch here: https://www.w3schools.com/js/js_api_fetch.asp

user2852263
  • 539
  • 4
  • 5