Convert SVG to image (JPEG, PNG, etc.) in the browser

I want to convert SVG into bitmap images (like JPEG, PNG, etc.) through JavaScript.

Here is how you can do it through JavaScript:

  1. Use the canvg JavaScript library to render the SVG image using Canvas:
  2. Capture a data URI encoded as a JPG (or PNG) from the Canvas, according to these instructions: Capture HTML Canvas as gif/jpg/png/pdf?

jbeard4 solution worked beautifully.

I'm using Raphael SketchPad to create an SVG. Link to the files in step 1.

For a Save button (id of svg is "editor", id of canvas is "canvas"):

$("#editor_save").click(function() {

// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("#editor").html());

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
// do what you want with the base64, write to screen, post to server, etc...

This seems to work in most browsers:

function copyStylesInline(destinationNode, sourceNode) {
   var containerElements = ["svg","g"];
   for (var cd = 0; cd < destinationNode.childNodes.length; cd++) {
       var child = destinationNode.childNodes[cd];
       if (containerElements.indexOf(child.tagName) != -1) {
            copyStylesInline(child, sourceNode.childNodes[cd]);
       var style = sourceNode.childNodes[cd].currentStyle || window.getComputedStyle(sourceNode.childNodes[cd]);
       if (style == "undefined" || style == null) continue;
       for (var st = 0; st < style.length; st++){
  [st], style.getPropertyValue(style[st]));

function triggerDownload (imgURI, fileName) {
  var evt = new MouseEvent("click", {
    view: window,
    bubbles: false,
    cancelable: true
  var a = document.createElement("a");
  a.setAttribute("download", fileName);
  a.setAttribute("href", imgURI);
  a.setAttribute("target", '_blank');

function downloadSvg(svg, fileName) {
  var copy = svg.cloneNode(true);
  copyStylesInline(copy, svg);
  var canvas = document.createElement("canvas");
  var bbox = svg.getBBox();
  canvas.width = bbox.width;
  canvas.height = bbox.height;
  var ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, bbox.width, bbox.height);
  var data = (new XMLSerializer()).serializeToString(copy);
  var DOMURL = window.URL || window.webkitURL || window;
  var img = new Image();
  var svgBlob = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
  var url = DOMURL.createObjectURL(svgBlob);
  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob)
        var blob = canvas.msToBlob();         
        navigator.msSaveOrOpenBlob(blob, fileName);
    else {
        var imgURI = canvas
            .replace("image/png", "image/octet-stream");
        triggerDownload(imgURI, fileName);
  img.src = url;

The solution to convert SVG to blob URL and blob URL to png image

const svg=`<svg version="1.1" baseProfile="full" width="300" height="200"
   <rect width="100%" height="100%" fill="red" />
   <circle cx="150" cy="100" r="80" fill="green" />
   <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text></svg>`
    const pngImage = document.createElement('img');
 function svgToPng(svg, callback) {
    const url = getSvgUrl(svg);
    svgUrlToPng(url, (imgData) => {
function getSvgUrl(svg) {
    return  URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
function svgUrlToPng(svgUrl, callback) {
    const svgImage = document.createElement('img');
    // = 'absolute';
    // = '-9999px';
    svgImage.onload = function () {
        const canvas = document.createElement('canvas');
        canvas.width = svgImage.clientWidth;
        canvas.height = svgImage.clientHeight;
        const canvasCtx = canvas.getContext('2d');
        canvasCtx.drawImage(svgImage, 0, 0);
        const imgData = canvas.toDataURL('image/png');
        // document.body.removeChild(imgPreview);
    svgImage.src = svgUrl;

Here's a server side solution based on PhantomJS. You can use JSONP to make a cross domain call to the image service:

For example:


Then you can display image with img tag:

<img src="data:image/png;base64, [base64 data]"/>

It works across browser.

I wrote this ES6 Class which does the Job.

class SvgToPngConverter {
  constructor() {
    this._init = this._init.bind(this);
    this._cleanUp = this._cleanUp.bind(this);
    this.convertFromInput = this.convertFromInput.bind(this);

  _init() {
    this.canvas = document.createElement("canvas");
    this.imgPreview = document.createElement("img"); = "position: absolute; top: -9999px";

    this.canvasCtx = this.canvas.getContext("2d");

  _cleanUp() {

  convertFromInput(input, callback) {
    let _this = this;
    this.imgPreview.onload = function() {
      const img = new Image();
      _this.canvas.width = _this.imgPreview.clientWidth;
      _this.canvas.height = _this.imgPreview.clientHeight;
      img.crossOrigin = "anonymous";
      img.src = _this.imgPreview.src;
      img.onload = function() {
        _this.canvasCtx.drawImage(img, 0, 0);
        let imgData = _this.canvas.toDataURL("image/png");
        if(typeof callback == "function"){

    this.imgPreview.src = input;

Here is how you use it

let input = ""
new SvgToPngConverter().convertFromInput(input, function(imgData){
    // You now have your png data in base64 (imgData). 
    // Do what ever you wish with it here.

If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.

change svg to match your element

function svg2img(){
    var svg = document.querySelector('svg');
    var xml = new XMLSerializer().serializeToString(svg);
    var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
    var b64start = 'data:image/svg+xml;base64,';
    var image64 = b64start + svg64;
    return image64;

Svg to png can be converted depending on conditions:

  1. If svg is in format SVG (string) paths:
    • create canvas
    • create new Path2D() and set svg as parameter
    • draw path on canvas
    • create image and use canvas.toDataURL() as src.


const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let svgText = 'M10 10 h 80 v 80 h -80 Z';
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
let url = canvas.toDataURL();
const img = new Image();
img.src = url;

Note that Path2D not supported in ie and partially supported in edge. Polyfill solves that:

  1. Create svg blob and draw on canvas using .drawImage():
    • make canvas element
    • make a svgBlob object from the svg xml
    • make a url object from domUrl.createObjectURL(svgBlob);
    • create an Image object and assign url to image src
    • draw image into canvas
    • get png data string from canvas: canvas.toDataURL();

Nice description:

Note that in ie you will get exception on stage of canvas.toDataURL(); It is because IE has too high security restriction and treats canvas as readonly after drawing image there. All other browsers restrict only if image is cross origin.

  1. Use canvg JavaScript library. It is separate library but has useful functions.


var dataURL = canvas.toDataURL();

I recently discovered a couple of image tracing libraries for JavaScript that indeed are able to build an acceptable approximation to the bitmap, both size and quality. I'm developing this JavaScript library and CLI :

Which provides unified API for all of them, supporting browser and node, non depending on DOM, and a Command line tool.

For converting logos/cartoon/like images it does excellent job. For photos / realism some tweaking is needed since the output size can grow a lot.

It has a playground although right now I'm working on a better one, easier to use, since more features has been added: