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.
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.
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.
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();
});