I want to send an inline SVG image to a PHP script to Convert it to PNG with Imagick. For that I have to know how to get a base64 String out on an inline SVG. For canvas objects its a simple ".toDataURL()" but that doesn't work with inline SVGs, because its not a global function of elements.
test = function(){
var b64 = document.getElementById("svg").toDataURL();
alert(b64);
}
http://jsfiddle.net/nikolang/ccx195qj/1/
But how to do it for inline SVGs?
You can do it relatively straightforwardly as follows. The short version is
svg
base64
encode the sourcesvg
, append the relevant data, setimg src
Get the
canvas
context;.drawImage
the imageJSFiddle: https://jsfiddle.net/oz3tjnk7/
I had the same problem while working on SVG based Floorplan Editor, after drawing a floorplan we have to save it for later use. Long story, code is better than talking, Here is the final code which worked for me:
I just try to collect and explain all great ideas on this issue. This works on both Chrome 76 and Firefox 68
This line will perform the conversion:
Make sure that the proper charset/encoding has been selected!
Use XMLSerializer to convert the DOM to a string
and then btoa can convert that to base64
Just prepend the data URL intro i.e.
data:image/svg+xml;base64,
and there you have it.