How to draw an inline svg (in DOM) to a canvas? How to draw an inline svg (in DOM) to a canvas? javascript javascript

How to draw an inline svg (in DOM) to a canvas?


For inline SVG you'll need to:

  • Convert the SVG string to a Blob
  • Get an URL for the Blob
  • Create an image element and set the URL as src
  • When loaded (onload) you can draw the SVG as an image on canvas
  • Use toDataURL() to get the PNG file from canvas.

For example:

function drawInlineSVG(ctx, rawSVG, callback) {    var svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}),        domURL = self.URL || self.webkitURL || self,        url = domURL.createObjectURL(svg),        img = new Image;    img.onload = function () {        ctx.drawImage(this, 0, 0);             domURL.revokeObjectURL(url);        callback(this);    };    img.src = url;}// usage:drawInlineSVG(ctxt, svgText, function() {    console.log(canvas.toDataURL());  // -> PNG data-uri});

Of course, console.log here is just for example. Store/transfer the string instead here. (I would also recommend adding an onerror handler inside the method).

Also remember to set canvas size using either the width and height attributes, or from JavaScript using properties.


I come long after since some other question raised from this one because the accepted answer may produce undesirable behavior.

@K3N solution is almost right, but I would go against the use of svgElement.outerHTML.
Instead, one should prefer new XMLSerializer().serializeToString(svgElement).

Also, the use of blob and of the URL API is not necessary and a simple dataURI has more compatibility accross browsers.

So a complete version of this would be :

function drawInlineSVG(svgElement, ctx, callback) {  var svgURL = new XMLSerializer().serializeToString(svgElement);  var img = new Image();  img.onload = function() {    ctx.drawImage(this, 0, 0);    callback();  }  img.src = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgURL);}// usage:drawInlineSVG(document.querySelector('svg'), ctxt, function() {  console.log(canvas.toDataURL())});