Skip to content

Instantly share code, notes, and snippets.

@caseywatts
Last active May 3, 2016 13:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save caseywatts/512c7cff7c4125a15c01 to your computer and use it in GitHub Desktop.
Save caseywatts/512c7cff7c4125a15c01 to your computer and use it in GitHub Desktop.
convert svg to png inline
// modified from answers on http://stackoverflow.com/questions/5433806/convert-embedded-svg-to-png-in-place
// Takes an SVG element as target
function svg_to_png_data(target) {
var ctx, mycanvas, svg_data, img, child;
// Construct an SVG image
var new_width = target.width.baseVal.valueInSpecifiedUnits;
var new_height = target.height.baseVal.valueInSpecifiedUnits;
svg_data = '<svg xmlns="http://www.w3.org/2000/svg" width="' + new_width +
'" height="' + new_height + '">' + target.innerHTML + '</svg>';
img = new Image();
img.src = "data:image/svg+xml;utf8," + svg_data;
// Draw the SVG image to a canvas
mycanvas = document.createElement('canvas');
mycanvas.width = new_width;
mycanvas.height = new_height;
ctx = mycanvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Return the canvas's data
return mycanvas.toDataURL("image/png");
}
// Takes an SVG element as target
function svg_to_png_replace(target) {
var data, img;
data = svg_to_png_data(target);
img = new Image();
img.src = data;
target.parentNode.replaceChild(img, target);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment