Convert SVG graph to png

Abstract

This article shows how to convert an SVG (scalable vector graphics) graph into a PNG image. The objective can be achieved with an image element that has an SVG source ('data:image/svg+xml,...') Further the image could be loaded in a canvas element allowing to do almost anything with the image created.

Rationale

In Google Chrome, a right mouse click on an SVG graph does not allow to store the drawing in a graphics format (only html is proposed). Internet Explorer allows to save an SVG drawing as .bmp or .png format. In our case, we want to provide a button, enabling the download of the created drawing.

SVG Drawing

In this section a simple circle is drawn via SVG. Try out the "change color" button in order to re-color the circle randomly and click on the download link afterwards.

<svg id="preview_svg" xmlns="https://www.w3.org/2000/svg" version="1.1" width="100" height="100">

    <circle id="svg_circle" cx="50" cy="50" r="30" fill="#456AA8" />

</svg>

Result


--> Click here to download as image (png)

Source

function getRandomInt(min, max) {

    return Math.floor(Math.random() * (max - min + 1)) + min;

}

 

function changeColor() {

    var c = document.querySelector('#svg_circle');

 

    var color = 'rgb(' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ')';

    c.setAttribute('fill', color);

    createDownloadLink();

}

       

function createDownloadLink() {

    var svgContainer = document.querySelector('#preview_svg');

    var svg = svgContainer.outerHTML;

    var canvas = document.querySelector("#drawOn"); // cnavas is hidden

    var ctx = canvas.getContext("2d");

 

    canvas.width = svgContainer.clientWidth;

    canvas.height = svgContainer.clientHeight;

 

    var img = new Image;

    img.src = 'data:image/svg+xml,' + encodeURIComponent(svg);

    img.onload = function () {

        ctx.drawImage(img, 0, 0);

        document.querySelector('#dlink').href = canvas.toDataURL("image/png");

    }

}

 

$(function () {

    createDownloadLink();

});

Sources

[1] Convert SVG to PNG

Links

https://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
https://jsfiddle.net/g2waggpb/2/
https://gist.github.com/Caged/4649511


Dieter Neumann