SVG which was created programmatically does not convert into base64 correctly.
In my application I've got a service which get a response with g-element and then put into created svg-element and convert it into base64, but if I try to open a link I find that svg does not render on the page.
var xmlns = 'http://www.w3.org/2000/svg',
IMAGE_TEMPLATE = document.createElementNS(xmlns, 'svg');
IMAGE_TEMPLATE.appendChild(document.body.querySelector('#ico-appliance-thermostat-128'));
IMAGE_TEMPLATE.setAttribute('id', 'svg');
IMAGE_TEMPLATE.setAttributeNS(null, 'width', 128);
IMAGE_TEMPLATE.setAttributeNS(null, 'height', 128);
IMAGE_TEMPLATE.setAttributeNS(null, 'viewBox', '0 0 128 128');
document.body.querySelector('#test').appendChild(IMAGE_TEMPLATE);
test = function(){
var s = new XMLSerializer().serializeToString(document.getElementById("svg"))
var encodedData = window.btoa(s);
console.log('data:image/svg+xml;base64,' + encodedData);
}
You didn't close test() with a }. Code below returns a base64 encoded svg: https://jsfiddle.net/seahorsepip/6sra5c5L/1/
Edit:
svg render issue is something I ran into myself before, here's the fix with a line of jquery: https://jsfiddle.net/seahorsepip/6sra5c5L/3/
Here's the original SO thread about the issue: jquery's append not working with svg element?
I don't know the javascript equivalent for the jQuery code I added, I tried to write it but it didn't work :/
Edit 2:
Here's the pure js equivalent:
https://jsfiddle.net/seahorsepip/6sra5c5L/4/
Try adding
<svg></svg>
around<g>
element , closing}
attest
function ; definingtest
as a named functionjsfiddle https://jsfiddle.net/6sra5c5L/5/
HTML elements and SVG elements have different namespaces. By putting the
<g>
element in your HTML you have created an<html:g>
element. When it is moved inside the<svg>
, it is still an<html:g>
and won't be recognised by the SVG renderer.You either have to put it inside soem
<svg>
tags as @guest271314 described. Or, after you append to the SVG, go through all the elements in the<g>
and change all their namespaces to the SVG one.