Created
February 18, 2014 15:27
-
Star
(114)
You must be signed in to star a gist -
Fork
(22)
You must be signed in to fork a gist
-
-
Save gustavohenke/9073132 to your computer and use it in GitHub Desktop.
SVG to PNG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var svg = document.querySelector( "svg" ); | |
var svgData = new XMLSerializer().serializeToString( svg ); | |
var canvas = document.createElement( "canvas" ); | |
var ctx = canvas.getContext( "2d" ); | |
var img = document.createElement( "img" ); | |
img.setAttribute( "src", "data:image/svg+xml;base64," + btoa( svgData ) ); | |
img.onload = function() { | |
ctx.drawImage( img, 0, 0 ); | |
// Now is done | |
console.log( canvas.toDataURL( "image/png" ) ); | |
}; |
sorry can somebody tell me what is container hier ? image Tag?
function svg_to_png(container) {
var wrapper = document.getElementById(container);
var svg = wrapper.querySelector("svg");
if (typeof window.XMLSerializer != "undefined") {
var svgData = (new XMLSerializer()).serializeToString(svg);
} else if (typeof svg.xml != "undefined") {
var svgData = svg.xml;
}
var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData))) );
img.onload = function() {
ctx.drawImage(img, 0, 0);
var imgsrc = canvas.toDataURL("image/png");
var a = document.createElement("a");
a.download = container+".png";
a.href = imgsrc;
a.click();
};
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if the svg element contains some
tag, these code seems not work