Illustrating Hubert OG 's answer with code; 2 remarks first.
First (thank you, Robert Longson), it might work without encodeURIComponent, but you better include it (for example, if you have something like fill="url(#pattern)" the encodeURIComponent is necessary, because of the # character)
Second, the SVG namespace is not optional, but it might not be included in svgElt.outerHTML. Especially, if you have created your svg node via createElementNS, like so
svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
then a subsequent call to svgElt.outerHTML will not contain the namespace attribute, and this would result in not working code, unless you include the namespace attribute later in some fashion
var imgEnc = new Image();
var imgEncNS = new Image();
var prefix = 'data:image/svg+xml,';
var svgOpen = '';
var svgOpenNS = '
you can fix the missing namespace issue by using function outerXHTML from my answer to this question
or like this
function imgFromSVGnode(node){
function setNS(elt, parentNS){
var namespace = elt.namespaceURI;
if (namespace!==parentNS){
elt.setAttribute('xmlns', namespace);
}
for (var i=0; i