JSFiddle - React, Tailwind, and code Playground
by chprpipr
HTML
<svg version="1.1" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<style type="text/css">
<![CDATA[
text {
font-size:60px;
text-anchor: middle;
fill:#FFFFFF;
}
]]>
</style>
<rect width="100%" height="100%" fill="#FF0000" />
<rect width="100%" height="50%" fill="#0000FF" />
<text x="150" y="70">SVG</text>
</svg>
<button onclick="exportPNG();">Export</button>
JavaScript
var exportPNG = function() {
/*
Based off gustavohenke's svg2png.js
https://gist.github.com/gustavohenke/9073132
*/
var svg = document.querySelector( "svg" );
var svgData = new XMLSerializer().serializeToString( svg );
var canvas = document.createElement( "canvas" );
var ctx = canvas.getContext( "2d" );
var dataUri = '';
try {
dataUri = 'data:image/svg+xml;base64,' + btoa(svgData);
} catch (ex) {
// For browsers that don't have a btoa() method, send the text off to a webservice for encoding
/* Uncomment if needed
$.ajax({
url: "http://www.mysite.com/webservice/encodeString",
data: { svg: svgData },
type: "POST",
async: false,
success: function(encodedSVG) {
dataUri = 'data:image/svg+xml;base64,' + encodedSVG;
}
})
*/
}
var img = document.createElement( "img" );
img.onload = function() {
ctx.drawImage( img, 0, 0 );
try {
// Try to initiate a download of the image
var a = document.createElement("a");
a.download = "MDMS_Graph_Export.png";
a.href = canvas.toDataURL("image/png");
document.querySelector("body").appendChild(a);
a.click();
document.querySelector("body").removeChild(a);
} catch (ex) {
// If downloading not possible (as in IE due to canvas.toDataURL() security issue)
// then display image for saving via right-click
var imgPreview = document.createElement("div");
imgPreview.appendChild(img);
document.querySelector("body").appendChild(imgPreview);
}
};
console.log(dataUri);
img.src = dataUri;
}