- Create an
img
and set its src to your SVG.
- Create an HTML5 canvas and use
drawImage()
to draw that image to your canvas.
- Use
toDataURL()
on the canvas to get a base64 encoded PNG.
- Create an img and set it's src to that data URL.
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 <svg>
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…