Skip to content

Instantly share code, notes, and snippets.

@riston
Created April 3, 2014 14:25
Show Gist options
  • Save riston/9955322 to your computer and use it in GitHub Desktop.
Save riston/9955322 to your computer and use it in GitHub Desktop.
Convert currently active svg to png, copy this to your web console and execute "svg2png(document.querySelector('svg'))", click the url to open.
// Takes an SVG element as target
function svg2png(target) {
// Flatten CSS styles into the SVG
for (i = 0; i < target.childNodes.length; i++) {
child = target.childNodes[i];
child.style.cssText = window.getComputedStyle(child).cssText;
}
var box = target.viewBox.baseVal;
// Construct an SVG image
svg_data = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="' + box.x + ' ' + box.y + ' ' + box.width + ' ' + box.height + '">' + target.innerHTML + '</svg>';
img = new Image();
img.src = "data:image/svg+xml," + encodeURIComponent(svg_data);
// Draw the SVG image to a canvas
var mycanvas = document.createElement('canvas');
mycanvas.width = target.clientWidth;
mycanvas.height = target.clientHeight;
var ctx = mycanvas.getContext("2d");
ctx.drawImage(img, 0, 0);
console.log(mycanvas.toDataURL("image/png"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment