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 = '<svg width="200" height="30">';
var svgClose = '</svg>';
var svgOpenNS = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="30">';
var rect = '<rect width="200" height="30" fill="black"/>';
var html = svgOpen + rect + svgClose;
var htmlNS = svgOpenNS + rect + svgClose;
var htmlEnc = window.encodeURIComponent(html);
var htmlEncNS = window.encodeURIComponent(htmlNS);
imgEnc.src = prefix + htmlEnc;
imgEncNS.src = prefix + htmlEncNS;
function T(txt){
document.body.appendChild(document.createTextNode(txt));
}
function HR(){ document.body.appendChild(document.createElement('hr')); }
function BR(){ document.body.appendChild(document.createElement('br')); }
function A(arg){ document.body.appendChild(arg); }
T('without namespace'); BR(); A(imgEnc); HR();
T('with namespace'); BR(); A(imgEncNS);
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<elt.childNodes.length; i++){
setNS(elt.childNodes[i], namespace);
}
}
setNS(node, null);
var html = node.outerHTML;
var dataURL = 'data:image/svg+xml,' + window.encodeURIComponent(html);
var img = new Image();
img.src = dataURL;
return img;
};