Skip to content

Instantly share code, notes, and snippets.

@cacheflowe
Last active November 27, 2016 17:53
Show Gist options
  • Save cacheflowe/99f4877f0daeac255ff4192ab28c84fe to your computer and use it in GitHub Desktop.
Save cacheflowe/99f4877f0daeac255ff4192ab28c84fe to your computer and use it in GitHub Desktop.
Render svg to bitmap
var renderSVG = function(svgEl, renderedCallback, jpgQuality) {
// WARNING! Inline <image> tags must have a base64-encoded image as their source. Linked image files will not work.
// transform svg into base64 image
var s = new XMLSerializer().serializeToString(svgEl);
var uri = 'data:image/svg+xml;base64,' + window.btoa(s);
// load svg image into canvas
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
if(jpgQuality > 0.2) {
var jpg = canvas.toDataURL('image/jpeg', jpgQuality);
renderedCallback(jpg);
} else {
var png = canvas.toDataURL('image/png');
renderedCallback(png);
}
}
image.src = uri;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment