I\'m generating HTML from a Docbook source while using SVG for images (converted from MathML). This works fine for some browsers that can interpret SVG, but fails for others
img
and set its src to your SVG.drawImage()
to draw that image to your canvas.toDataURL()
on the canvas to get a base64 encoded PNG.var mySVG = document.querySelector('…'), // Inline SVG element
tgtImage = document.querySelector('…'), // Where to draw the result
can = document.createElement('canvas'), // Not shown on page
ctx = can.getContext('2d'),
loader = new Image; // Not shown on page
loader.width = can.width = tgtImage.width;
loader.height = can.height = tgtImage.height;
loader.onload = function(){
ctx.drawImage( loader, 0, 0, loader.width, loader.height );
tgtImage.src = can.toDataURL();
};
var svgAsXML = (new XMLSerializer).serializeToString( mySVG );
loader.src = 'data:image/svg+xml,' + encodeURIComponent( svgAsXML );
However, this answer (and all client-side only solutions) require the browser to support SVG, which may make it useless for your specific needs.
Edit: This answer assumes that the SVG is available as a separate URL. Due to the problems described in this question I cannot get the above to work with an SVG document embedded in the same document performing the work.
Edit 2: The problems described in that other question have been overcome by improvements to Chrome and Firefox. There is still the limitation that the element must have
width="…" height="…"
attributes for Firefox to allow it to be drawn to a canvas. And Safari currently taints the entire canvas whenever you draw any SVG to it (regardless of source) but that should change soon.