I have an svg
tag like this:
<svg id="targetSvg" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 150 150">
<polyline points="5 5 100 20 40 80 20 10" style="stroke: blue; stroke-width: 2px; fill: none;"></polyline>
</svg>
I implemented a function to modify the svg tag content with javascript
,
and downloaded the modified content like this:
const a = document.createElement('a');
a.setAttribute('download', 'download.svg');
a.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(document.getElementById('targetSvg').outerHTML));
a.click();
And then I reuploaded the downloaded file to my website and displayed it like this:
<img id='img' src="download.svg" style="width: 800px; height:500px;" />
This works perfectly fine.
So I expected that this would also work:
document.getElementById('img').setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(document.getElementById('targetSvg').outerHTML));
But it doesn’t. It just doesn’t show the image without any errors. What did I do wrong?
I also tried the following, but none of them worked:
document.getElementById('img').setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(document.getElementById('targetSvg').outerHTML));
document.getElementById('img').setAttribute('href', 'data:image/svg+xml,' + encodeURIComponent(document.getElementById('targetSvg').outerHTML));
document.getElementById('img').setAttribute('href', await new Promise(async (res) => {
const reader = new FileReader();
reader.onload = () => res(reader.result);
reader.readAsDataURL(new Blob([document.getElementById('targetSvg').outerHTML], { type: 'image/svg+xml' }));
}));