Convert embedded SVG to PNG in-place

Demo: http://phrogz.net/SVG/svg_to_png.xhtml

  1. Create an img and set its src to your SVG.
  2. Create an HTML5 canvas and use drawImage() to draw that image to your canvas.
  3. Use toDataURL() on the canvas to get a base64 encoded PNG.
  4. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)